效果
具体实现
1. 添加依赖
implementation 'com.android.support:design:28.0.0'
2.添加TabLayout和ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_below="@id/tab"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
TabLayout相关属性参考
https://blog.csdn.net/qq_27853161/article/details/56489147
3.创建ViewPager的适配器
class ViewPagerAdapter(fm: FragmentManager, fragmentList: List<Fragment>, titleList: List<String>) : FragmentPagerAdapter(fm) {
private var fragmentList = fragmentList
private var titleList = titleList
override fun getItem(p0: Int): Fragment {
return fragmentList[p0]
}
override fun getCount(): Int {
return fragmentList.size
}
override fun getPageTitle(position: Int): CharSequence? {
return titleList[position]
}
}
4.创建Fragment及其对应的布局
Fragment1
class Fragment1 : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//Fragment1对应的布局文件为page1.xml
return inflater.inflate(R.layout.page1,container,false)
}
}
布局文件page1.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="50sp"
android:text="Page 1"/>
</android.support.constraint.ConstraintLayout>
5.完成绑定
class MainActivity : AppCompatActivity() {
private var fragmentList = arrayListOf<Fragment>()
private var titleList = arrayListOf("tab1","tab2","tab3")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var fragment1 = Fragment1()
var fragment2 = Fragment2()
var fragment3 = Fragment3()
fragmentList.add(fragment1)
fragmentList.add(fragment2)
fragmentList.add(fragment3)
var fm = supportFragmentManager
//设置viewpager的适配器
container.adapter = ViewPagerAdapter(fm,fragmentList,titleList)
//默认显示第一个页面
container.currentItem = 0
//tablayout与viewpager绑定
tab.setupWithViewPager(container,true)
}
}