android Tablayout的使用

这里写图片描述
以往我们想要实现这样的效果,要么去找三方开源库,要么自己动手写viewpager,然后根据viewpager的滑动计算指示器的滑动距离来实现。现在在google提供的design包里有一个tablayout可以帮助我们快速实现。

<android.support.design.widget.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/mainColor"
            app:tabIndicatorColor="@color/white"
            app:tabSelectedTextColor="@color/white"
            app:tabTextColor="@color/white"
            >
        </android.support.design.widget.TabLayout>
        <android.support.v4.view.ViewPager
            android:layout_below="@+id/tablayout"
            android:id="@+id/vp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></android.support.v4.view.ViewPager>

来看布局文件,首先是tablayout,然后在下面写一个viewpager控件。tablayout中app:tabIndicatorColor表示指示器颜色,app:tabSelectedTextColor表示被选择时候文字颜色,app:tabTextColor表示默认颜色。

 tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
        vp = (ViewPager) view.findViewById(R.id.vp);
        fragmentList = new ArrayList<>();
        fragmentList.add(new Fragment1());
        fragmentList.add(new Fragment2());
        fragmentList.add(new Fragment3());
        fragmentList.add(new Fragment4());
        adapter = new MyAdapter (getActivity().getSupportFragmentManager(),fragmentList);
        vp.setAdapter(adapter);
        tabLayout.setupWithViewPager(vp);

通过tablayout的setupWidthViewPager就可以把tablayout和viewpager关联起来。
再来看看adapter:


public class MyAdapter extends FragmentPagerAdapter {
    private List<Fragment> list_fragment;                         //fragment列表
    private String[]  list_Title = new String[]{"标题1","标题2","标题3","标题4"};
    public MyAdapter (android.support.v4.app.FragmentManager fm, List<Fragment> list_fragment) {
        super(fm);
        this.list_fragment = list_fragment;
    }

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

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

    @Override
    public CharSequence getPageTitle(int position) {
        return list_Title[position];
    }
}

getpageTitle方法里返回各个position要知道的标题就可以在tablayout中正常显示title了。
这样就完成了简单的tablayout的使用。
如果使用的时候发现滑动时文字有闪烁现象,可以把desigin包升级下就没有问题了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章