android 自动选中中心tab,滚动停止后选中tab自动回滚到布局中心的CenterSelectTabLayout

github地址

无图无真相
在这里插入图片描述

项目中需要实现类似效果,找了几个库都不行,封装一下供大家copy

CenterSelectTabLayout继承自Recyclerview,CenterSelectTabLayoutAdapter继承自RecyclerView.Adapter,使用起来和RecyclerView基本一样

如何使用:

  • add dependency
implementation 'com.sign.centerselecttablayout:centerselecttablayout:1.0.1'
  • init view
<com.sign.centerselecttablayout.view.CenterSelectTabLayout
    android:id="@+id/centerSelectTabLayout"
    android:layout_width="match_parent"
    android:layout_height="60dp" />

val exampleAdapter = ExampleAdapter()
centerSelectLayout.adapter = exampleAdapter
  • init adapter ( 为了处理centerSelectLayout.scrollToPosition(),需要实现这个方法 )
/**
 * Return 选中tab的一半宽度 单位像素
 */
abstract fun getHalfOfSelectTabWidth(scrollPosition: Int): Int
  • init listener ( 设置当tab被选中时的监听 )
exampleAdapter.centerSelectTabLayoutListener = object :
    CenterSelectTabLayoutAdapter.CenterSelectTabLayoutListener(
        centerSelectLayout,
        exampleAdapter
    ) {
    override fun onTabSelect(position: Int) {
        super.onTabSelect(position)
    }
}
  • scrollToPosition or smoothScrollToPosition ( 请求数据完毕或其它你需要设置初始选中tab的情况 )
centerSelectLayout.smoothScrollToPosition(10)
//centerSelectLayout.scrollToPosition(10)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章