TabLayot+ViewPage+RecycleView切换tab

一、前言:

在开发中遇到ViewPage2+RecycleView横向滑动时,会出现滑动冲突,换成ViewPage+RecycleView就不会出现滑动冲突。

二、TabLayot+ViewPage+RecycleView切换tab使用:

1、TestDemo
/**
 * 测试demo
 */
class TestDemo : BaseActivity<NewMainViewModel, ActivityTestDemoBinding>(2) {
    val tabList = arrayListOf<String>("tab1", "tab2", "tab3")
    val mainScope = MainScope()

    //fragment页面
    val fragmentList by lazy { ArrayList<Fragment>() }

    override fun initView(savedInstanceState: Bundle?) {
        initTabButton2()
    }

    private fun initTabButton2() {
        try {
            tabList.forEachIndexed { _index, it ->
                //创建tab
                val tab = mViewBind.tablayout.newTab()
                //自定义布局
                tab.setCustomView(R.layout.vip_tab_item)
                tab.customView?.findViewById<TextView>(R.id.tab_name)?.text = it
                mViewBind.tablayout.addTab(tab)

                var fragment = TestFragment().apply {

                    val bundle = Bundle()
                    bundle.putString("type_position", "${_index + 1}")
                    arguments = bundle
                }
                fragmentList.add(fragment)
            }

            var myAdapter = MyAdapter(fragmentList, supportFragmentManager)
            mViewBind.viewpager.adapter = myAdapter
            //默认第一个选中
            val tabFirst = mViewBind.tablayout.getTabAt(0)
            tabFirst?.select()
            updateTabView(tabFirst, true)

            //点击tabLayout时调用
            mViewBind.tablayout.addOnTabSelectedListener(object :
                TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    try {//更新按钮选中状态

                        //注意:由于tablayout和viewPage2没有关联,所以点击按钮不会切换,只会显示第一个页面,左右滑动没有问题,所以在此手动切换fragment的跳转。
                        //获取对应的下标
                        var position = tab?.position ?: 0
                        //跳转对应的fragment页面
                        mViewBind.viewpager.currentItem = position
                        updateTabView(tab, true)
                    } catch (e: Exception) {
                        MyToash.Log("lyy", "---报错4:${e.toString()}")
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    updateTabView(tab, false)
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })



            mViewBind.viewpager.setOnPageChangeListener(object :
                ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    try {//左右滑动时调用
                        mViewBind.tablayout.getTabAt(position)?.select()
                    } catch (e: Exception) {
                        MyToash.Log("lyy", "---报错3:${e.toString()}")
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })


        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


    /**
     * 更新tab的字体大小、颜色或者下划线显示
     */
    private fun updateTabView(tab: TabLayout.Tab?, isSelect: Boolean) {
        try {
            Log.d("home", "updateTabView: tab=${tab?.position}, isSelectd=$isSelect")
            tab?.customView.let {
                val tabName: TextView? = it?.findViewById(R.id.tab_name)
                val ivIndicator: ImageView? = it?.findViewById(R.id.iv_indicator)

                if (isSelect) {
                    //设置字体类型、大小
                    val paint = tabName?.paint
                    paint?.isFakeBoldText = true
                    tabName?.textSize = 14f
                    //下划线显示
                    ivIndicator?.visibility = View.VISIBLE
                    //设置tab字体颜色
                    tabName?.setTextColor(ContextCompat.getColor(this, R.color.colorAccent))

                } else {
                    //设置字体类型、大小
                    val paint = tabName?.paint
                    paint?.isFakeBoldText = false
                    tabName?.textSize = 14f
                    //下划线隐藏
                    ivIndicator?.visibility = View.INVISIBLE
                    //设置tab字体颜色
                    tabName?.setTextColor(ContextCompat.getColor(this, R.color.color_FF4512A0))
                }
            }
        } catch (e: Exception) {
            MyToash.Log("lyy", "---报错2:${e.toString()}")
        }
    }
}

2、activity_test_demo.xml
<?xml version="1.0" encoding="utf-8"?><!--主页面布局-->
<LinearLayout 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"
    android:orientation="vertical">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/ui_dp_60"
        android:background="@mipmap/x_home_bottom_tab_bg"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cl_top"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/transparent"
        app:tabIndicatorFullWidth="false"
        app:tabIndicatorHeight="4dp"
        app:tabMinWidth="50dp"
        app:tabMode="fixed"
        app:tabPaddingEnd="12dp"
        app:tabPaddingStart="12dp"
        app:tabRippleColor="@android:color/transparent" />

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

3、MyAdapter
package com.youjiakeji.yjkjreader.kotlin.ui.adapter.multi.customer;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.List;

public class MyAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragmentList;

    public MyAdapter(List<Fragment> fragmentList, FragmentManager fm) {
        super(fm);
        this.fragmentList = fragmentList;
    }

    @Override
    public Fragment getItem(int i) {
        return fragmentList.get(i);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }
}

4、vip_tab_item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data></data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

        <TextView
            android:id="@+id/tab_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全部"
            android:textColor="@color/color_FFB19CCC"
            android:textSize="@dimen/ui_sp_14"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/iv_indicator"
            android:layout_width="@dimen/ui_dp_20"
            android:layout_height="@dimen/ui_dp_4"
            android:layout_marginTop="@dimen/ui_dp_3"
            android:background="@drawable/x_shape_2_bg_fb9a63"
            android:visibility="invisible"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tab_name" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

5、TestFragment.kt
class TestFragment  : BaseFragment<NewMineViewModel, FragmentTestBinding>() {
    val mianAdapter by lazy { MyTestDemoAdapter() }
    override fun initView(savedInstanceState: Bundle?) {
        var bundle = getArguments()
       var type_position = bundle?.getString("type_position") ?: "0"

        mViewBind.tvContent.text = "这是第${type_position} 页面"

        when(type_position){
            "1" ->{
               mViewBind.llBg.setBackgroundResource(R.color.gray_9)
            }
           "2" ->{
               mViewBind.llBg.setBackgroundResource(R.color.maincolor_75)
            }

            "3" ->{
                mViewBind.llBg.setBackgroundResource(R.color.comic_info_tag_text)
            }
        }

        initList()
    }

    private fun initList() {
        var list = arrayListOf<String>("1","1","1","1","1","1","1")
       mViewBind.rvList.apply {
           var linearLayoutManager = LinearLayoutManager(context)
           linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
           layoutManager = linearLayoutManager
           adapter = mianAdapter
       }

        mianAdapter.setList(list)
    }

}

6、fragment_test.xml
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout
        android:id="@+id/ll_bg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="哈哈哈哈哈"
            />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</layout>

7、MyTestDemoAdapter
class MyTestDemoAdapter:BaseQuickAdapter<String,BaseDataBindingHolder<ItemTestDemoBinding>> (R.layout.item_test_demo){
    override fun convert(holder: BaseDataBindingHolder<ItemTestDemoBinding>, item: String) {
        val adapterPosition = holder.adapterPosition

        if (adapterPosition%2==0){
            holder.dataBinding?.tvTitle?.setBackgroundResource(R.color.color_774BC2)
        }else{
            holder.dataBinding?.tvTitle?.setBackgroundResource(R.color.color_FFF573D5)
        }
    }
}

8、item_test_demo.xml
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>

    </data>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginVertical="@dimen/ui_dp_10"
        android:layout_marginHorizontal="@dimen/ui_dp_15"
        android:background="@color/gray_9"
        >

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="@dimen/ui_dp_100"
            android:layout_height="@dimen/ui_dp_100"
            android:background="#f00"
            android:text="我是方块"
            android:gravity="center"
            android:textColor="@color/white"
            />
    </LinearLayout>
</layout>

最后

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。
img
相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。

欢迎大家一键三连支持,若需要文中资料,直接扫描文末CSDN官方认证微信卡片免费领取↓↓↓

PS:群里还设有ChatGPT机器人,可以解答大家在工作上或者是技术上的问题
图片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值