TabLayout+ViewPager2+Fragment简单使用(kotlin)

CSDN话题挑战赛第2期
参赛话题:学习笔记

布局文件

activity_main.xml


<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:layout_width="match_parent"
        android:layout_height="40dp"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/tab_main"/>
    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/tab_main"
        app:layout_constraintBottom_toBottomOf="parent"
        android:id="@+id/viewPager2_main"/>
androidx.constraintlayout.widget.ConstraintLayout>

news_fragment.xml


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:text="新闻"/>
androidx.constraintlayout.widget.ConstraintLayout>

创建Fragment

class NewsFragment : Fragment(){
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.news_fragment, container, false)
        return view
    }
}

Fragment适配器

class FragmentAdapter(fragment: FragmentActivity, val datas: List<Fragment>) : FragmentStateAdapter(fragment){
    override fun getItemCount(): Int {
        return datas.size
    }

    override fun createFragment(position: Int): Fragment {
        return datas[position]
    }
}

MainActivity

val newTypeList = listOf<String>("今日要闻","专题聚焦","政策解读")
//开始进行TabLayout+ViewPager2+Fragment操作
val newsFragmentList = mutableListOf<Fragment>()
for(i in newTypeList!!){
	newsFragmentList.add(NewsFragment())
}
//实例化适配器
val fragmentAdapter = FragmentAdapter
(this@MainActivity, newsFragmentList)
//设置适配器
viewPager2_main.adapter = fragmentAdapter
//TabLayout和Viewpager2进行关联
TabLayoutMediator(tab_main,viewPager2_main)
	{tab, position ->
		tab.text = newTypeList[position]
	}.attach()

最后

  1. 使用TabLayout需要
    implementation “com.google.android.material:material:1.1.0”
  2. id ‘kotlin-android-extensions’ 可以在kotlin中不使用findViewById()

你可能感兴趣的:(kotlin,android)