TabLayout + ViewPager切换Fragment

(1)创建布局

MainActivity的布局




    
    

    
    


(2)创建ViewPager的adapter

class PageAdapter(fm: FragmentManager): FragmentStatePagerAdapter(fm) {

    private val mPageFragment = ArrayList()
    private val mTitles = ArrayList()

    override fun getItem(p0: Int) = mPageFragment[p0]

    override fun getCount() = mPageFragment.size

    override fun getPageTitle(position: Int): CharSequence? {
        return mTitles[position]
    }

    fun addPage(page: PageFragment, name: String){
        mPageFragment.add(page)
        mTitles.add(name)
    }
}

(3)ViewPager绑定adapter,TabLayout绑定ViewPager

class MainActivity : AppCompatActivity() {

    private val titles = ArrayList()
    private lateinit var mPagerAdapter: PageAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initData()
    }

    private fun initData() {
        titles.add("热门")
        titles.add("娱乐")
        titles.add("游戏")
        mPagerAdapter = PageAdapter(supportFragmentManager)
        for (i in 0 until titles.size){
            val page = PageFragment()
            mPagerAdapter.addPage(page,titles[i])
            mPagerAdapter.notifyDataSetChanged()
        }
        mViewPager.adapter = mPagerAdapter
        mViewPager.offscreenPageLimit = 100
        mTabLayout.setupWithViewPager(mViewPager)
    }
}

(4)运行结果

运行结果

你可能感兴趣的:(TabLayout + ViewPager切换Fragment)