效果图
关键代码
TabLayout
继承自HorizontalScrollView
,见下图源码:
TabLayout
也是Google在support兼容包中新引入的新控件,它一般与ViewPager
及Fragment
组合使用实现滑动的标签选择器。具体实现源码如下,setupWithViewPager(viewPager)
设置ViewPager
,getTabAt(0)!!.select()
默认选中第一个标签。
MainActivity
代码如下:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
val viewPager = findViewById<ViewPager>(R.id.viewPager)
viewPager.adapter = SimpleFragmentPagerAdapter(supportFragmentManager)
tabLayout.setupWithViewPager(viewPager)
tabLayout.getTabAt(0)!!.select()
}
private inner class SimpleFragmentPagerAdapter constructor(fm: FragmentManager):
FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
private val titles = arrayOf("Tab1", "Tab2", "Tab3")
private val fragments = arrayOf(Fragment1(), Fragment1(), Fragment1())
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
override fun getPageTitle(position: Int): CharSequence? {
return titles[position]
}
}
}
MainActivity
布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabSelectedTextColor="@color/purple_200"
app:tabIndicatorHeight="2dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
为了演示TabLayout
与ViewPager
及Fragment
的用法,在MainActivity
中三个标签都使用的相同的Fragment1
,实际使用时应该用不同的Fragment
。
Fragment1
代码如下:
class Fragment1 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment, container, false)
}
}
Fragment1
的布局文件只有一个TextView
显示一行文本,具体如下:
<FrameLayout 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:text="Fragment 1"
android:textSize="20sp"/>
</FrameLayout>
源码地址
https://github.com/yurensan/MaterialDesignDemo
我是予人三,希望大家点赞支持我哦~ 有大家的鼓励我会分享更多内容