欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 使用TabLayout制作下划线能滑动的Tab标签页-design

程序员文章站 2022-06-01 07:51:05
...

原文地址: https://blog.csdn.net/zhuwentao2150/article/details/52279133


google提供的Design开发包里,有很多实用好看的新控件,这里介绍下使用TabLayout+ViewPager实现下划线能滑动的Tab标签页

效果图 
Android 使用TabLayout制作下划线能滑动的Tab标签页-design 
不使用google的design包,我们也可以自己制作这样的效果,详看我的这篇博客:http://blog.csdn.net/zhuwentao2150/article/details/51407661

要使用Design包,在项目的build.gradle中添加下依赖就好(记得更新SDK到最新版本)

dependencies {
     compile 'com.android.support:design:23.4.0'
}
  • 1
  • 2
  • 3

先来看布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:tabSelectedTextColor="#ffffff"
        app:tabIndicatorColor="#ff00ff"
        app:tabTextColor="#000000"
        app:tabIndicatorHeight="5dp"
        app:tabMode="fixed"/>

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

</LinearLayout>

常用属性 
tabSelectedTextColor:当Tab标签被选中时的文字颜色 
tabTextColor:Tab标签中文字的默认颜色 
tabIndicatorColor:下划线颜色 
tabIndicatorHeight:下划线的高度 
tabBackground:设置Tab标签的背景 
tabMode:Tab标签的行为模式

MODE_FIXED: Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs. 
MODE_SCROLLABLE: Scrollable tabs display a subset of tabs at any given moment, and can contain longer tab labels and a larger number of tabs. They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels. This mode is commonly used with a ViewPager.

两种模式的差异: 
tabMode=”scrollable” 
滚动模式,TabLayout可以滚动 
标签多时,TabLayout支持滑动查看 
Android 使用TabLayout制作下划线能滑动的Tab标签页-design 
标签少时,,这些Tab会挤在一侧,且各个Tab不是等量分布的,有的占地多有的占地少 
Android 使用TabLayout制作下划线能滑动的Tab标签页-design

tabMode=”fixed” 
填充模式,TabLayout不可滚动,所有的Tab都被限制在一定区域内 
标签多时,Tab会受到挤压 
Android 使用TabLayout制作下划线能滑动的Tab标签页-design

Tab少时,各个Tab等量空间分布 
Android 使用TabLayout制作下划线能滑动的Tab标签页-design

Fragment页面

/**
 * ViewPager页面
 * Created by zhuwentao on 2016-08-22.
 */
public class ViewPagerFragment extends Fragment{

    private String mPageNo;

    private TextView mPageNoTv;

    /** 状态类型常量 */
    public static final String STATUS_TYPE = "pagerType";

    public static final String STATUS_ONE = "One";

    public static final String STATUS_TWO = "Two";

    public static final String STATUS_THREE = "Three";

    /**
     * 取得Fragment实例
     */
    public static ViewPagerFragment newInstance(Bundle args) {
        ViewPagerFragment fragment = new ViewPagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNo = getArguments().getString(STATUS_TYPE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_tab, container, false);
        mPageNoTv = (TextView) v.findViewById(R.id.tv_page_text);
        mPageNoTv.setText(mPageNo);
        return v;
    }

}

Activity界面

public class TabLayoutActivity extends AppCompatActivity {

    private ViewPager mPageVp;

    private TabLayout mLayoutTab;

    /**
     * 选项卡总数
     */
    private static final int TAB_COUNT = 3;

    private static final int TAB_0 = 0;

    private static final int TAB_1 = 1;

    private static final int TAB_2 = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);
        initUI();
    }

    /**
     * 初始化UI
     */
    private void initUI() {
        mPageVp = (ViewPager) findViewById(R.id.vp_tab_pager);
        mLayoutTab = (TabLayout) findViewById(R.id.tab_layout);

        mPageVp.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        // 把TabLayout和ViewPager关联起来
        mLayoutTab.setupWithViewPager(mPageVp);
    }

    /**
     * ViewPager适配器
     */
    public class MyPagerAdapter extends FragmentPagerAdapter {

        // 定义Tab标题
        private String[] tabTitles = new String[]{
                "One","Two","Three"
        };

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Bundle args = new Bundle();
            boolean flag = true;
            switch (position) {
                case TAB_0:
                    args.putString(ViewPagerFragment.STATUS_TYPE, ViewPagerFragment.STATUS_ONE);
                    break;
                case TAB_1:
                    args.putString(ViewPagerFragment.STATUS_TYPE, ViewPagerFragment.STATUS_TWO);
                    break;
                case TAB_2:
                    args.putString(ViewPagerFragment.STATUS_TYPE, ViewPagerFragment.STATUS_THREE);
                    break;
                default:
                    flag = false;
                    break;
            }
            if (flag) {
                // 返回对应的Fragment页面
                return ViewPagerFragment.newInstance(args);
            }
            return null;
        }

        @Override
        public int getCount() {
            return TAB_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // 设置Page对应的Tab标题
            return tabTitles[position];
        }
    }

}

调用setupWithViewPager()方法传入一个ViewPager对象,请确保该ViewPager对象已经通过setAdapter设置好了Adapter适配器 
从源码可以看出

public void setupWithViewPager(@Nullable final ViewPager viewPager) {
    if (mViewPager != null && mPageChangeListener != null) {
        // If we've already been setup with a ViewPager, remove us from it
        mViewPager .removeOnPageChangeListener( mPageChangeListener);
    }

    if (viewPager != null ) {
        final PagerAdapter adapter = viewPager.getAdapter();
        if (adapter == null) {
            throw new IllegalArgumentException( "ViewPager does not have a PagerAdapter set");
        }
    // ......

如果ViewPager的Adapter为空,则会抛出IllegalArgumentException异常 
把 TabLayout和 ViewPager 关联起来,该方法相当于帮我们封装好了 addOnPageChangeListener 和setOnTabSelectedListener ,帮我们节省了大量的代码。