Skip to content

Instantly share code, notes, and snippets.

@yasukotelin
Last active February 14, 2022 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasukotelin/e0942a9f3f441b058efbaaab901ec890 to your computer and use it in GitHub Desktop.
Save yasukotelin/e0942a9f3f441b058efbaaab901ec890 to your computer and use it in GitHub Desktop.
Tabの要素数によってTab Modeを切り替えるExtension
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