Last active
February 14, 2022 09:12
-
-
Save yasukotelin/e0942a9f3f441b058efbaaab901ec890 to your computer and use it in GitHub Desktop.
Tabの要素数によってTab Modeを切り替えるExtension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.ViewGroup | |
import com.google.android.material.tabs.TabLayout | |
/** | |
* Tab表示が画面に収まる場合と収まらない場合とでTab mode指定を切り替える | |
* | |
* Tabサイズが画面に収まる場合は[TabLayout.MODE_FIXED] | |
* Tabサイズが画面に収まらない場合は[TabLayout.MODE_SCROLLABLE] | |
*/ | |
fun TabLayout.adjustTabMode() { | |
this.tabMode = TabLayout.MODE_SCROLLABLE | |
this.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> | |
var totalWidth = 0 | |
val tabLayoutGroup = this.getChildAt(0) as ViewGroup | |
for (i in 0 until this.tabCount) { | |
val tab = tabLayoutGroup.getChildAt(i) | |
val tabWidth = tab?.width ?: 0 | |
totalWidth += tabWidth | |
} | |
// 全タブ幅が許容サイズ内に収まっているかどうか | |
val isFixedTabsWidth = totalWidth < width | |
if (isFixedTabsWidth) { | |
this.tabMode = TabLayout.MODE_FIXED | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment