TabLayout简单使用

TabLayout是Google官方在5.0时为开发者提供的标签布局,一般情况下TabLayout都是跟ViewPager合在一起使用,用简单的代码就能实现ViewPager页面跟顶部标签的联动,废话不多说,直接贴代码。

SDK版本小于5.0时需要在.gradle文件中添加依赖:

compile 'com.android.support:design:25.0.1'

布局文件很简单,就一个TabLayout,一个ViewPager

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabSelectedTextColor="@color/colorAccent"></android.support.design.widget.TabLayout>

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

ViewPager的Adaper直接继承FragmentPagerAdapter,这里需要注意的是,要想TabLayout跟ViewPager关联,需要重写getPageTitle()方法,此方法返回TabLayout的Item的标题

public class MyAdapter extends FragmentPagerAdapter{

    private List<Fragment> fragments;
    private List<String> titles;

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

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

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

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

用来填充ViewPager的Fragment:

public class ToutiaoFragment extends Fragment {

    private LinearLayout linearLayout;
    private TextView tab;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_toutiao, container, false);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
        tab = (TextView) view.findViewById(R.id.tab);
        if (getArguments() != null) {
            //取出保存的值
            linearLayout.setBackgroundColor(getResources().getColor(getArguments().getInt("backgroundColor")));
            tab.setText(getArguments().getString("tab"));
        }
        return view;
    }

    public static ToutiaoFragment newInstance(String tab, int backgroundColor) {
        ToutiaoFragment toutiaoFragment = new ToutiaoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("tab", tab);
        bundle.putInt("backgroundColor", backgroundColor);
        //fragment保存参数,传入一个Bundle对象
        toutiaoFragment.setArguments(bundle);
        return toutiaoFragment;
    }
}

Activity代码:

public class TabLayoutActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    private List<Fragment> fragments;
    private List<String> titles;

    // 头条,社会,国内,娱乐,体育,军事,科技,财经,时尚

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tablayout);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewPager);

        fragments = new ArrayList<Fragment>();
        fragments.add(ToutiaoFragment.newInstance("头条新闻", R.color.mediumaquamarine));
        fragments.add(ToutiaoFragment.newInstance("社会新闻", R.color.cornflowerblue));
        fragments.add(ToutiaoFragment.newInstance("国内新闻", R.color.cadetblue));
        fragments.add(ToutiaoFragment.newInstance("娱乐新闻", R.color.darkolivegreen));
        fragments.add(ToutiaoFragment.newInstance("体育新闻", R.color.indigo));
        fragments.add(ToutiaoFragment.newInstance("军事新闻", R.color.mediumturquoise));

        titles = Arrays.asList(getResources().getStringArray(R.array.titles));

        viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), fragments, titles));
        tabLayout.setupWithViewPager(viewPager);
    }

}

TabLayout通过setupWithViewPager()方法与ViewPager关联起来。

运行效果图
这里写图片描述

到这里大致效果已经出来了,由于我们没有对TabLayout的属性进行设置,所有Item默认充满并平分整个TabLayout的长度,这显然并不时我们想要的。如果想要Item能够滑动,只需设置tabMode属性。
tabMode=”fixed”默认的显示模式,item充满并平分TabLayout的长度
tabMode=”scrollable”当item总长度超过TabLayout长度时,item随ViewPager滑动

下面是一些TabLayout常用属性的介绍:

tabSelectedTextColor:选中时item标题的颜色
tabTextColor:默认item标题的颜色
tabIndicatorColor:导航条颜色
tabBackground:标签的背景,可通过drawable文件设置tab点击选中效果

以上是TabLayout与ViewPager关联时的简单使用方法,如果TabLayout单独使用,则需要手动添加TabItem。

布局中添加TabItem:

<android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="体育新闻" />
    </android.support.design.widget.TabLayout>

代码中添加TabItem:

 tabLayout.addTab(tabLayout.newTab().setText("头条新闻"));

通过addOnTabSelectedListener()设置相应的点击事件

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 选择时调用
                if (tab.getText().equals("头条新闻")) {
                    Toast.makeText(TabLayoutActivity.this, "头条新闻onTabSelected", Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 为选择时调用
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 连续选择时调用
            }
        });

手动添加TabItem可以设置item的icon,title,layout运用起来比较灵活,
TabLayout的简单使用就介绍到这里,如果系统的控件不能满足需求,可以使用github上的开源控件
FlycoTabLayout
MagicIndicator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值