美文网首页
TabLayot+ViewPage+RecycleView切换t

TabLayot+ViewPage+RecycleView切换t

作者: 因为我的心 | 来源:发表于2023-07-10 17:28 被阅读0次

一、前言:

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

为什么viewpager2和recyclerview 有横向滑动冲突.png 为什么viewpager和recyclerview 没有横向滑动冲突.png

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

示例图1.png 示例图2.png

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>

相关文章

  • Jupyter Notebook 更换主题

    安装 命令行参数 切换主题 使用 jt -l 可列出可用的主题名: 使用 jq -t 主题名 -T -N 可以切换...

  • 3DMAX快捷键

    视图操作 放大选中的视图:Alt+W 切换到顶视图:T 切换到透视图:P 切换到前视图:F 切换到左视图:L 切换...

  • Mac下 rtf转txt 快捷键

    command+shift+t 可以来回切换rtf、txt

  • LINUX

    切换到grid目录下 su - grid 查询监听实例状态 crsctlstatres-t exit 切换到数据库...

  • Ubuntu + terminal 快捷键

    Ubuntu 切换程序 逆向切换程序 终端 clear 清屏,将当前行上移 reset 清除 新...

  • 终端常用快捷键(持续更新中...)

    终端开启新终端窗口:Ctrl + Alt + T当前窗口开启新终端标签页 : Ctrl + Shift + T切换...

  • 2018-04-06

    关于iterm2的快捷操作: 全屏互相切换 cmd + enter 加新标签 cmd + t 切换标签 cmd+ ...

  • SDDM 启动黑屏

    SDDM 0.16 isn't started automatically by systemd 由于之前在切换各...

  • Another git process seems to be

    切换分支突然git 异常:Another git process seems to be running in t...

  • MAC iterm2 常用快捷键大全

    标签 新建标签:command + t 关闭标签:command + w 切换标签:command + 数字 / ...

网友评论

      本文标题:TabLayot+ViewPage+RecycleView切换t

      本文链接:https://www.haomeiwen.com/subject/gtneudtx.html