(1)創(chuàng)建布局
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)創(chuàng)建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)
}
}