【问题标题】:How to set snapping behaviour for TabLayout如何为 TabLayout 设置吸附行为
【发布时间】:2018-10-06 12:49:00
【问题描述】:

我使用TabLayout 来显示不同标签的图标和名称。使用TabLayout,我使用ViewPager 为每个选项卡添加FragmentsTabLayout 带有可点击的标签(并且它们在点击时居中)正在工作,但我想实现与 RecyclerView SnapHelper 相同的功能。如果我滚动TabLayout 选项卡,它会将视图捕捉到屏幕中心并选择它。这应该在TabLayout 下显示Fragment

有什么办法吗?

这是我的自定义 TabLayout,它会将点击的视图居中放置在中间。

class CenteredTabLayout : TabLayout {
    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        val firstTab = (getChildAt(0) as ViewGroup).getChildAt(0)
        val lastTab = (getChildAt(0) as ViewGroup).getChildAt((getChildAt(0) as ViewGroup).childCount - 1)
        if (firstTab != null && lastTab != null){
            ViewCompat.setPaddingRelative(getChildAt(0), width / 2 - firstTab.width / 2, 0, width / 2 - lastTab.width / 2, 0)
        }
    }
}

【问题讨论】:

    标签: android android-fragments android-viewpager android-tablayout


    【解决方案1】:

    TabLayout selected tab gravity

    tl;dr 使用默认的 TabLayout,您无法修改对齐效果。因为计算其移动距离的方法calculateScrollXForTab是私有的,无法替代。

    我也想用我的 TabLayout 做一些自定义的捕捉。最终我放弃了,并为标签创建了我自己的 RecyclerView 和适配器。我不需要 TabLayout 提供的指标(创建了我的自定义指标)。所以我所要做的就是使用我的适配器实现ViewPager.OnPageChangeListener

    还阅读了其他源代码对滚动的真正帮助。

    例如https://github.com/nshmura/RecyclerTabLayout

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 2021-08-17
      • 2016-06-17
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      相关资源
      最近更新 更多