其他分享
首页 > 其他分享> > TabLayout+ViewPager2+Fragment实现页面切换

TabLayout+ViewPager2+Fragment实现页面切换

作者:互联网

如图:

1、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:tabIndicator="@color/transparent"
        app:tabRippleColor="@color/transparent"
        app:tabIndicatorColor="@color/transparent"
        app:tabBackground="@color/transparent"
        app:tabIndicatorFullWidth="false"
        style="@style/CustomTabLayout"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </com.google.android.material.tabs.TabLayout>
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tab_layout"
        app:layout_constraintBottom_toBottomOf="parent">
    </androidx.viewpager2.widget.ViewPager2>



</androidx.constraintlayout.widget.ConstraintLayout>

 2、创建适配器继承 FragmentStateAdapter

package com.example.tablayoutdemo

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter

class GuideViewPagerAdapter (fragmentManager: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(fragmentManager,lifecycle){
    override fun getItemCount(): Int {
        return 3
    }

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> {
                OneFragment()
            }
            1 -> {
                TwoFragment()
            }
            2 -> {
                ThreeFragment()
            }
            else -> {
                OneFragment()
            }
        }
    }

}

3、MainActivity

package com.example.tablayoutdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class MainActivity : AppCompatActivity() {

    private lateinit var guideViewPagerAdapter: GuideViewPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
        val viewPager = findViewById<ViewPager2>(R.id.view_pager)

        guideViewPagerAdapter = GuideViewPagerAdapter(supportFragmentManager, lifecycle)
        viewPager.adapter = guideViewPagerAdapter
        TabLayoutMediator(tabLayout,viewPager){ tab, position ->
            val inflater = LayoutInflater.from(tab.parent?.context)
            val binding = inflater.inflate(R.layout.tab_item_indicator, tab.view, false)
            Log.i("打印11:","$position")
            val tvName = binding.findViewById<TextView>(R.id.tv_name)
            if (position == 0){
                tvName.text = "one"
                tvName.setTextSize(20F)
                tvName.setBackgroundResource(R.drawable.btn_select)
            }else if (position == 1){
                tvName.text = "two"
            }else if (position == 2){
                tvName.text = "three"
            }

            tab.customView = binding
        }.attach()


        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val customView = tab?.customView as ConstraintLayout
                val tvName = customView.findViewById<TextView>(R.id.tv_name)
                tvName.setTextSize(20F)
                Log.i("打印222:","${tab?.position}")
                /*if (tab?.position == 0){
                    tvName.text = "one"
                }else if (tab!!.position == 1){
                    tvName.text = "two"
                }else if (tab!!.position == 2){
                    tvName.text = "three"
                }*/
                tvName.setBackgroundResource(R.drawable.btn_select)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                val customView = tab?.customView as ConstraintLayout
                val tvName = customView.findViewById<TextView>(R.id.tv_name)
                Log.i("打印333:","${tab?.position}")
               /* if (tab?.position == 0){
                    tvName.text = "one"
                }else if (tab!!.position == 1){
                    tvName.text = "two"
                }else if (tab!!.position == 2){
                    tvName.text = "three"
                }*/
                tvName.setTextSize(16F)
                tvName.setBackgroundResource(R.drawable.btn_select_no)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                val customView = tab?.customView as ConstraintLayout
                val tvName = customView.findViewById<TextView>(R.id.tv_name)
                Log.i("打印444:","${tab?.position}")
                /*if (tab?.position == 0){
                    tvName.text = "one"
                }else if (tab!!.position == 1){
                    tvName.text = "two"
                }else if (tab!!.position == 2){
                    tvName.text = "three"
                }*/
                tvName.setTextSize(18F)
                tvName.setBackgroundResource(R.drawable.btn_select)
            }

        })



    }
}

4、tab_item_indicator.xml

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/tv_name"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:text=""
        android:gravity="center"
        android:textSize="16sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"></TextView>
    <ImageView
        android:id="@+id/iv_img"
        android:src="@mipmap/ic_launcher"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_name"></ImageView>

</androidx.constraintlayout.widget.ConstraintLayout>

5、btn_select

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--填充色-->
    <!--<solid android:color="#FF409DFE"></solid>-->
    <solid android:color="#F4F4F4"></solid>

    <!-- 矩形的边线 -->
   <!-- <stroke android:color="#4B4B4B"
        android:width="0.5dp"></stroke>-->

    <!--圆角大小-->
    <corners
        android:bottomRightRadius="20dp"
        android:topRightRadius="20dp"
        android:topLeftRadius="20dp"
        android:bottomLeftRadius="20dp"></corners>
    <!--android:radius="10dp"-->

    <!--android:topLeftRadius="7dp"
    android:bottomLeftRadius="7dp"-->
</shape>

6、btn_select_no

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--填充色-->
    <!--<solid android:color="#FF409DFE"></solid>-->
    <solid android:color="#FFFFFF"></solid>

    <!--<!– 矩形的边线 –>
    <stroke android:color="#4B4B4B"
        android:width="0.5dp"></stroke>-->

    <!--圆角大小-->
    <corners
        android:bottomRightRadius="20dp"
        android:topRightRadius="20dp"
        android:topLeftRadius="20dp"
        android:bottomLeftRadius="20dp"></corners>
    <!--android:radius="10dp"-->

    <!--android:topLeftRadius="7dp"
    android:bottomLeftRadius="7dp"-->
</shape>

 7、styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CustomTabLayout" parent="Widget.Design.TabLayout">
        <item name="tabGravity">center</item>
        <item name="tabMode">fixed</item>
        <item name="tabIndicatorFullWidth">false</item>

        <item name="android:background">@null</item>
        <item name="tabIconTint">@null</item>
        <item name="tabMaxWidth">@dimen/design_tab_max_width</item>
        <item name="tabIndicatorAnimationDuration">@integer/design_tab_indicator_anim_duration_ms</item>
        <item name="tabIndicatorColor">@color/transparent</item>
        <item name="tabIndicatorGravity">bottom</item>
        <item name="tabIndicatorAnimationMode">linear</item>
        <item name="tabIndicator">@color/transparent</item>
        <item name="tabPaddingStart">12dp</item>
        <item name="tabPaddingEnd">12dp</item>
        <item name="tabTextAppearance">@style/TextAppearance.Design.Tab</item>
        <item name="tabTextColor">@null</item>
        <item name="tabRippleColor">@color/transparent</item>
        <item name="tabUnboundedRipple">false</item>
    </style>
</resources>

  

 

 完成

 

标签:val,Fragment,import,text,tab,tvName,ViewPager2,position,TabLayout
来源: https://www.cnblogs.com/changyiqiang/p/15750166.html