美文网首页
TabLayout + ViewPager切换Fragment

TabLayout + ViewPager切换Fragment

作者: PeterWu丷 | 来源:发表于2019-06-16 23:25 被阅读0次

(1)创建布局

MainActivity的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tl_tab"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

</LinearLayout>

(2)创建ViewPager的adapter

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

    private val mPageFragment = ArrayList<PageFragment>()
    private val mTitles = ArrayList<String>()

    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<String>()
    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

      本文链接:https://www.haomeiwen.com/subject/rninfctx.html