TabLayout实现ViewPager指示器

在TabLayout出现之前,基本都是通过 ViewPager+FragmentPagerAdapter+第三方开源tab指示器(TabPageIndicator)来实现的。现在Android内部提供了现成的TabLayout控件来实现ViewPager指示器的效果。

先看效果图:

这里写图片描述


导入依赖

在Gradle文件中导入依赖,代码如下:

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

TabLayout类就在这个依赖包中定义的。

布局文件中使用

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="tech.czh.example.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="top"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white">

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

</LinearLayout>

在LinearLayout中使用TabLayout标签和ViewPager标签。

Activity代码编写

public class MainActivity extends AppCompatActivity
{

    public static final String[] tabTitles =
            new String[]{"短信1","短信2","短信3","短信4","短信5","短信6","短信7","短信8","短信9"};

    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private List<SingleFragment> mFragments = new ArrayList<SingleFragment>();

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

        initViews();
    }

    private void initViews()
    {
        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);

        for(int i = 0; i < tabTitles.length; i++)
        {
            mFragments.add(SingleFragment.createFragment(tabTitles[i]));
        }

        //为ViewPager设置FragmentPagerAdapter
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager())
        {
            @Override
            public Fragment getItem(int position)
            {
                return mFragments.get(position);
            }

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

            /**
             * 为TabLayout中每一个tab设置标题
             */
            @Override
            public CharSequence getPageTitle(int position)
            {
                return tabTitles[position];
            }
        });

        //TabLaout和ViewPager进行关联
        mTabLayout.setupWithViewPager(mViewPager);
        //防止tab太多,都拥挤在一起
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }
}

大部分功能都在initViews()方法中实现,大致讲解一下:第23,24行获得TabLayout和ViewPager控件实例;26~29行创建了需要的Fragment实例,并保存在mFragments列表中。第32行,为ViewPager设置FragmentPagerAdapter,并通过getSupportFragmentManager()方法将FragmentManager传递给FragmentPagerAdapter。第50行,getPageTitle()回调函数,来为TabLayout中的Tab设置标题。第57行,将TabLayout和ViewPager进行关联。最后,设置了TabLayout的模式,TabLayout.MODE_SCROLLABLE表示TabLayout可以滑动,这样就可以防止过多的Tab拥挤在一屏内。

Fragment代码编写

public class SingleFragment extends Fragment
{
    public static final String ARGUMENT = "ARGUMENT";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        Bundle bundle = getArguments();
        String text = "";
        if(bundle != null) {
            text = bundle.getString(ARGUMENT);
        }
        TextView tv = new TextView(getActivity());
        tv.setText(text);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
        tv.setGravity(Gravity.CENTER);

        return tv;
    }

    public static SingleFragment createFragment(String argument)
    {
        Bundle bundle = new Bundle();
        bundle.putString(ARGUMENT, argument);

        SingleFragment fragment = new SingleFragment();
        fragment.setArguments(bundle);

        return fragment;
    }
}

Fragment的UI控件很简单,仅仅包含一个TextView。外部通过静态方法createFragment()用来创建Fragment实例,并且可以传递参数,传递的参数将设置到TextView中。

OK,至此TabLayout就可以正常使用了,效果就为文章开始贴的gif图。


另外,TabLayout还提供了很多自定义属性,让我们自定义Tab的样式。

示例代码:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="tech.czh.example.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="top"
        app:tabTextColor="@color/colorPrimary"
        app:tabSelectedTextColor="@color/colorAccent"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabIndicatorHeight="5dp"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white">

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

</LinearLayout>

这里我们使用一些属性,比如:tabTextColor用来设置Tab中文字颜色;
tabSelectedTextColor用来设置Tab被选中时文字颜色;tabIndicatorColor用来设置指示器颜色;tabIndicatorHeight用来设置指示器的高度。

最后,看一下效果:

这里写图片描述


好的,TabLayout的使用就说这么多。可以看出TabLayout使用起来还是很方便的,并且最终效果也很nice。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最近接到一个任务,就是要修改原来用的官方support包TabLayout中的指示器线宽,改成固定值,当然网上有什么反射加padding什么的,可是治标不治本,切Tab过渡动画也加不了,什么?你告诉我github又xxx类似控件,可是为什么我要放弃google大神的源码呢,改改就能增加新功能了呢,为了达到目的,我就开始了下面一系列骚操作。0. 老规矩,先放效果图1. 骚操作之一:copy support包TabLayout 一份当做自己的自定义view本次骚操作是基于support '27.1.0'版本,从support '27.1.0'拷出文件到我的项目目录如下图,蓝色部分,四个文件,当然不是一帆风顺的,需要改点包名,取消掉一下注解警告,总之后面会放出源码 不同的版本可能需要拷贝出来的文件不一样哟,于support '27.1.0'版本需要拷出上图蓝色的4个文件2. 骚操作之二: fuck源代码,读懂之后开始改造首先指示器的线是画出来的,关键代码如下 (以下改动代码均为tabLayout类)   canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight,                             mIndicatorRight, getHeight(), mSelectedIndicatorPaint);OK, mIndicatorLeft是滚动或者点击切tab时候通过偏移量计算出来的,总之不重要,完成第一个目标。修改指示器线宽,思路呢,就是给mIndicatorLeft和mIndicatorRight做一个偏移量就行了, 看看我怎么改的吧其中2个成员变量是我在SlidingTabStrip类中新增的 private int mSelectedIndicatorWidth =  dpToPx(27);;         private int mMinTabWidth = Integer.MAX_VALUE;我这里偷懒一下就不做方法暴露了,直接写死了线宽为27dp了好了,已经完成修改线宽目标了。(扩展一下:这里你也可以修改draw方法,画个图,或者画个小圆圈什么的)接下来增加指示线滑动切tab的过渡动画很简单我就放代码吧,关键就是在onPageScrolled方法里面做点手脚总共改动就50来行吧,就达成效果了。是不是很简单。(简单才怪,总之做出来之后觉得确实蛮简单的) 这样改好处多多,为什么呢?xml基本不需要改变,tablayout名字改一下,代码也是导包改一下,替换官方tablayout的时候代码几乎不需要变化,是不是很爽?3. github下载,喜欢就给个star吧,如果对你有帮助的话https://github.com/zjw-swun/AppOrder4. 总结官方support包就是可以这么任性的拷贝出来,有时候一个拷出一个类根本没涉及到别的类,善假于物也。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值