ViewPager2 和TabLayout 的使用

 谷歌地址 https://github.com/android/views-widgets-samples

 优点

可自定义下标长度

可实现fragment的可视再进行加载 ,

可实现垂直或者横向滑动展示

//design 变为如下
implementation "com.google.android.material:material:1.0.0"
implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha01'

 



 适配器变更如下

class BaseFragmentStateAdapter(fragmentManager: FragmentManager) :
    FragmentStateAdapter(fragmentManager) {

    fun add(fragment: Fragment) {
        mFragments.add(fragment)
    }
    private val mFragments = mutableListOf()
    override fun getItem(position: Int): Fragment {
        return mFragments[position]
    }

    override fun getItemCount(): Int {
        return mFragments.size
    }
}

主界面

class ViewPage2Activity : AppCompatActivity() {
    private lateinit var fragmentAdapter: BaseFragmentStateAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_page2)
        initFragment()
    }

    private fun initFragment() {
        fragmentAdapter = BaseFragmentStateAdapter(supportFragmentManager)
        fragmentAdapter.add(LoginFragment())
        fragmentAdapter.add(RegisterFragment())
        fragmentAdapter.add(LoginFragment())
        mViewPager.adapter = fragmentAdapter
        //        TabLayout和ViewPager的绑定
        val tabLayoutMediator =
            TabLayoutMediator(mTabLayout, mViewPager,
                OnConfigureTabCallback { tab, position ->
                    tab.text = "Tab$position" })
        tabLayoutMediator.attach()
    }
}

 

你可能感兴趣的:(TabLayout相关问题)