如何为TabLayout设置捕捉行为

问题描述 投票:0回答:1

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

有什么方法可以做到吗?

这是我的自定义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个回答
0
投票

TabLayout selected tab gravity

tl; dr使用默认的TabLayout,您无法修改捕捉效果。因为计算其移动的calculateScrollXForTab的距离的方法是私人的,不能被替换。

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

另外阅读其他源代码如何滚动确实帮助了我。

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

© www.soinside.com 2019 - 2024. All rights reserved.