To use Android Material Tab, follow the steps below:

  1. Add the Material Design library to your project. You can do this by adding the following line to your build.gradle file:
implementation 'com.google.android.material:material:1.2.1'
  1. Create a new layout file for your tab layout. This layout file should contain a TabLayout view and a ViewPager view. The TabLayout view will display the tabs, and the ViewPager view will display the content for each tab.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:tabMode="scrollable"
        android:tabTextColor="@android:color/white"
        android:tabSelectedTextColor="@android:color/white"
        android:tabIndicatorColor="@android:color/white"
        android:tabIndicatorHeight="4dp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
  1. Create a new Fragment or Activity for each tab. These Fragments or Activities will contain the content for each tab.

  2. Create a new adapter for the ViewPager. This adapter will be responsible for creating the Fragments or Activities for each tab.

class TabAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

    private val fragments = mutableListOf<Fragment>()
    private val titles = mutableListOf<String>()

    fun addFragment(fragment: Fragment, title: String) {
        fragments.add(fragment)
        titles.add(title)
    }

    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]
    }

}
  1. In your Activity or Fragment, initialize the TabLayout and ViewPager views, and set the adapter for the ViewPager.
val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
val viewPager = findViewById<ViewPager>(R.id.view_pager)

val adapter = TabAdapter(supportFragmentManager)
adapter.addFragment(FirstFragment(), "First Tab")
adapter.addFragment(SecondFragment(), "Second Tab")
adapter.addFragment(ThirdFragment(), "Third Tab")

viewPager.adapter = adapter
tabLayout.setupWithViewPager(viewPager)
  1. Run your app and test the tab layout. You should see the tabs displayed at the top of the screen, and the content for each tab displayed in the ViewPager below.
how to use android material tab

原文地址: https://www.cveoy.top/t/topic/b4E8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录