TabLayout+ViewPager

本文介绍如何在Android应用中使用TabLayout组件实现标签页切换效果,包括依赖配置、XML布局设置、数据绑定及自定义下划线样式。同时,解决了ScrollView嵌套ViewPager时出现的显示与滚动冲突问题。

依赖:

implementation 'com.android.support:design:27.1.1'

xml布局

 <android.support.design.widget.TabLayout
        android:id="@+id/order_tab"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_28"
        android:layout_below="@id/text1"
        app:tabIndicatorColor="@color/colorRed"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/colorRed"
        app:tabTextColor="@color/colorBlack">

    </android.support.design.widget.TabLayout>


    <android.support.v4.view.ViewPager
        android:id="@+id/order_vpger"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/text">

    </android.support.v4.view.ViewPager>

添加数据:

  private void initData() {
        tab_sell = new ArrayList<>();
        tab_sell.add("全部");
        tab_sell.add("代付款");
        tab_sell.add("代发货");
        tab_sell.add("代收货");
        tab_sell.add("代评价");

        fragment_sell = new ArrayList<>();
        fragment_sell.add(new OrderAllFragment());
        fragment_sell.add(new OrderDfkFragment());
        fragment_sell.add(new OrderDfhFragment());
        fragment_sell.add(new OrderDshFragment());
        fragment_sell.add(new OrderDpjFragment());

    }

初始化,绑定适配器

 private void initViewPager() {
//        viewpager适配器
        mOrderVpger.setAdapter(new MyOrderPagerAdapter(getSupportFragmentManager(), fragment_sell, tab_sell));
//        绑定TabLayout
        mOrderTab.setupWithViewPager(mOrderVpger);

    }

viewpager适配器

public class MyOrderPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragment_sell;
    private List<String> tab_sell;


    public MyOrderPagerAdapter(FragmentManager fm, List<Fragment> fragment_sell, List<String> tab_sell) {
        super(fm);
        this.fragment_sell = fragment_sell;
        this.tab_sell=tab_sell;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return tab_sell.get(position);
    }

    @Override
    public Fragment getItem(int position) {
        return fragment_sell.get(position);
    }

    @Override
    public int getCount() {
        return fragment_sell.size();
    }
}
//    自定义设置下划线长度
    @Override
    public void onStart() {
        super.onStart();
        mSyTab.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(mSyTab, 25, 25);
            }
        });
    }
//    初始化下划线长度
    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }


    }

设置tablayout下划线长度的方法

public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
    Class<?> tabLayout = tabs.getClass();
    Field tabStrip = null;
    try {
        tabStrip = tabLayout.getDeclaredField("mTabStrip");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

    tabStrip.setAccessible(true);
    LinearLayout llTab = null;
    try {
        llTab = (LinearLayout) tabStrip.get(tabs);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
    int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

    for (int i = 0; i < llTab.getChildCount(); i++) {
        View child = llTab.getChildAt(i);
        child.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
        params.leftMargin = left;
        params.rightMargin = right;
        child.setLayoutParams(params);
        child.invalidate();
    }


}

需要用的时候,,只要在有tablayout的地方就可以用了

使用的方法如下面的代码所示

这里面直接post了这个,并开了Runnable,然后设置当前的tablayout的对象,并设置长度就可以了

@Override
public void onStart() {
    super.onStart();
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            setIndicator(tabLayout, 50, 50);
        }
    });
}

ScrollView嵌套ViewPager+Fragment时冲突问题解决办法

1.ViewPager 中的Fragment 不显示
给xml中ScrollView设置android:fillViewport=”true” 属性。通过这个就可以让ViewPager中的内容显示。
顾名思义,这个属性允许 NestedScrollView中的组件去充满它。

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/com_bg_gray_eeeeee"

                android:descendantFocusability="blocksDescendants"
                android:orientation="vertical">

                <com.bigkoo.convenientbanner.ConvenientBanner
                    android:id="@+id/acty_main_cbanner"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/comm_dim_150" />

                <android.support.design.widget.TabLayout
                    android:id="@+id/acty_main_tab"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/comm_dim_40"
                    android:layout_alignParentBottom="true"
                    app:tabBackground="@drawable/selector_tab_bg"
                    app:tabIndicatorHeight="0dp"
                    app:tabSelectedTextColor="@color/com_tv_white_ffffff"
                    app:tabTextAppearance="@style/tab_txtSize"
                    app:tabTextColor="@color/com_tv_black_333333" />

                <android.support.v4.view.ViewPager
                    android:id="@+id/acty_main_vp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>


        </android.support.v4.widget.NestedScrollView>

2.上下拖动ViewPager 不能垂直方向滚动

最开始使用的默认的ViewPager,发现不能上下滑动,然后通过查找别人的解决办法,NestedScrollView嵌套ViewPager后,如果viewPager中的fragment高度太长,会发现滑动不了,需要自定义ViewPager,测量ViewPager的高度.

public class WrapContentHeightViewPager extends ViewPager {
    public WrapContentHeightViewPager(Context context) {
        super(context);  
    }  

    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);  
    }  

    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);  

        int height = 0;  
        for (int i = 0; i < getChildCount(); i++) {  
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));  
            int h = child.getMeasuredHeight();  
            if (h > height) height = h;  
        }  
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);  
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
    }  
}  

然后将xml布局的ViewPager替换为我们自定义的ViewPager

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/com_bg_gray_eeeeee"

                android:descendantFocusability="blocksDescendants"
                android:orientation="vertical">

                <com.bigkoo.convenientbanner.ConvenientBanner
                    android:id="@+id/acty_main_cbanner"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/comm_dim_150" />

                <android.support.design.widget.TabLayout
                    android:id="@+id/acty_main_tab"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/comm_dim_40"
                    android:layout_alignParentBottom="true"
                    app:tabBackground="@drawable/selector_tab_bg"
                    app:tabIndicatorHeight="0dp"
                    app:tabSelectedTextColor="@color/com_tv_white_ffffff"
                    app:tabTextAppearance="@style/tab_txtSize"
                    app:tabTextColor="@color/com_tv_black_333333" />

                <com.aoben.qproj.widget.WrapContentHeightViewPager
                    android:id="@+id/acty_main_vp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>


        </android.support.v4.widget.NestedScrollView>
### 集成 TabLayoutViewPager 实现标签页滑动功能 在 Android 开发中,结合 `TabLayout` 和 `ViewPager` 可以快速实现带有标签页的滑动界面,这种模式广泛应用于顶部标签页(如知乎)和底部菜单栏(如微信)等场景。`TabLayout` 提供了可视化的标签指示器,而 `ViewPager` 负责页面的滑动切换,两者结合可以实现高度交互性的 UI 效果。 #### 添加依赖 在使用 `TabLayout` 和 `ViewPager` 前,需要在模块的 `build.gradle` 文件中添加对 `com.android.support:design` 的依赖。例如: ```gradle implementation 'com.android.support:design:26+' ``` 该依赖包含了 `TabLayout` 控件,并确保其与 `ViewPager` 的兼容性[^2]。 #### 布局文件配置 在 XML 布局文件中,需要定义 `TabLayout` 和 `ViewPager` 的位置。以下是一个典型的布局示例: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" /> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` 其中,`TabLayout` 用于显示标签页,而 `ViewPager` 则用于承载各个页面内容。 #### 设置适配器 为了实现 `ViewPager` 与 `Fragment` 的集成,通常使用 `FragmentPagerAdapter` 或 `FragmentStatePagerAdapter` 作为适配器。以下是一个使用 `FragmentPagerAdapter` 的示例: ```java public class MyFragmentPagerAdapter extends FragmentPagerAdapter { private List<Fragment> fragmentList; public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) { super(fm); this.fragmentList = fragmentList; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return "Tab " + (position + 1); // 设置标签页标题 } } ``` 在 `getPageTitle` 方法中返回的字符串将作为 `TabLayout` 中每个标签页的标题。 #### 绑定 TabLayoutViewPager 在 `Activity` 或 `Fragment` 中,通过 `setupWithViewPager` 方法将 `TabLayout` 与 `ViewPager` 进行绑定: ```java TabLayout tabLayout = findViewById(R.id.tabLayout); ViewPager viewPager = findViewById(R.id.viewPager); List<Fragment> fragments = new ArrayList<>(); fragments.add(new FragmentOne()); fragments.add(new FragmentTwo()); MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); ``` 通过 `setupWithViewPager` 方法,`TabLayout` 会自动根据 `ViewPager` 的页面数量生成对应的标签页,并实现页面切换与标签点击的联动效果[^1]。 #### 自定义 TabLayout 样式 `TabLayout` 支持自定义标签页的样式,包括字体颜色、背景、图标等。例如,可以通过 `setTabTextColors` 方法设置标签页文字的颜色: ```java tabLayout.setTabTextColors(Color.parseColor("#999999"), Color.parseColor("#FF0000")); ``` 还可以通过 `addTab` 方法手动添加带有图标或自定义视图的标签页,以实现更丰富的视觉效果。 #### 性能优化建议 - **缓存页面数量**:通过 `viewPager.setOffscreenPageLimit(int limit)` 设置预加载页面数量,避免频繁的页面销毁和重建,尤其适用于页面中包含 `WebView` 或复杂 UI 的情况[^2]。 - **懒加载机制**:对于需要延迟加载数据的 `Fragment`,可以通过 `setUserVisibleHint` 或 `FragmentStatePagerAdapter` 的 `instantiateItem` 方法实现懒加载,提升初始加载性能。 - **动画效果**:结合 `ViewPager.PageTransformer` 可以实现自定义的页面切换动画,增强用户体验。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值