Android-ViewPagerIndicator自定义tab数量

在上篇Android-ViewPagerIndicator简单集成的基础上,我们想开发类似网易新闻tab标签的功能,可以添加删除tab。

 

查看TabPageIndicator的源码我们可以看到有一个notifyDataSetChanged()方法。
public void notifyDataSetChanged() {
        mTabLayout.removeAllViews();
        PagerAdapter adapter = mViewPager.getAdapter();
        IconPagerAdapter iconAdapter = null;
        if (adapter instanceof IconPagerAdapter) {
            iconAdapter = (IconPagerAdapter)adapter;
        }
        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            CharSequence title = adapter.getPageTitle(i);
            if (title == null) {
                title = EMPTY_TITLE;
            }
            int iconResId = 0;
            if (iconAdapter != null) {
                iconResId = iconAdapter.getIconResId(i);
            }
            addTab(i, title, iconResId);
        }
        if (mSelectedTabIndex > count) {
            mSelectedTabIndex = count - 1;
        }
        setCurrentItem(mSelectedTabIndex);
        requestLayout();
    }

我们理解一下:

mTabLayout.removeAllViews();

mTabLayout是什么?

mTabLayout是IcsLinearLayout类型的,IcsLinearLayout是什么东西?

察看源码就很容易看出来,IcsLinearLayout其实是放tab的容器,继承LinearLayout,tab都放在这里面展示。里面封装了tab的样式:字体大小,颜色,间隔,分割线的样式等等。不是很难就不介绍了。

notifyDataSetChanged的第一行就是mTabLayout.removeAllViews();清空所有的tab。

 

继续看代码,PagerAdapter adapter = mViewPager.getAdapter();获取了mViewPager的适配器,这个适配器我们一般都是关联着一个fragment的列表。

 

 

继续

for (int i = 0; i < count; i++) {

            CharSequence title =adapter.getPageTitle(i);

            if (title == null) {

                title = EMPTY_TITLE;

            }

            int iconResId = 0;

            if (iconAdapter != null) {

                iconResId =iconAdapter.getIconResId(i);

            }

            addTab(i, title, iconResId);

        }

会将适配器中的每个item都拿出来构建一个tab加入到mTabLayout中。

 

最后刷新页面。

 

主体思路:清空所有的tab,重新加载tab,到了这里我们就知道怎么实现类似网易新闻tab的功能了吧 。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值