Android ViewPager2 & TabLayout,那些被大厂优化的程序员们
dependencies {// For the latest version number of ViewPager2, please refer to the official page.// Link: https://developer.android.com/jetpack/androidx/releases/viewpager2implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha04'}
XML 布局
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical">
<com.google.android.material.tabs.TabLayoutandroid:id="@+id/tabLayout"android:layout_width="match_parent"android:layout_height="wrap_content"/>
<androidx.viewpager2.widget.ViewPager2android:id="@+id/viewpager"android:layout_width="match_parent"android:layout_height="240dp"/></LinearLayout>
定义 RecyclerView Adapter 和单元布局
class DemoViewPagerAdapter : RecyclerView.Adapter<DemoViewPagerAdapter.EventViewHolder>() {val eventList = listOf("0", "1", "2")
// Layout "layout_demo_viewpager2_cell.xml" will be defined lateroverride fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =EventViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.layout_demo_viewpager2_cell, parent, false))
override fun getItemCount() = eventList.count()override fun onBindViewHolder(holder: EventViewHolder, position: Int) {(holder.view as? TextView)?.also{it.text = "Page " + eventList.get(position)
val backgroundColorResId = if (position % 2 == 0) R.color.blue else R.color.orange)it.setBackgroundColor(ContextCompat.getColor(it.context, backgroundColorResId))}}
class EventViewHolder(val view: View) : RecyclerView.ViewHolder(view)}
<?xml version="1.0" encoding="utf-8"?><TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:textSize="20sp"android:gravity="center"/>
使用 ViewPager2 绑定 RecyclerView Adapter
class ViewPager2Activity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.layout_view_pager_demo)viewpager.adapter = DemoViewPagerAdapter()}}
TabLayout 无法与 ViewPager2 绑定
但是在StackOverFlow中找到了解决方案,我们可以使用TabLayoutMediator实现 TabLayout 与 ViewPager2 的绑定。
TabLayoutMediator 不能直接使用,所以需要拷贝一份出来,根据代码注释可知 TabLayoutMediator 只能在初始化之后才能调用 attach 方法:
class ViewPager2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_view_pager2)
// Must be declared before TabLayoutMediator.attach()v
iewpager.adapter = DemoViewPagerAdapter()TabLayoutMediator(tabLayout, viewpager, object : TabLayoutMediator.OnConfigureTabCallback {override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
评论