为TabLayout添加角标的最简单方法
ugya3224
8年前
<h2><strong>一、前言</strong></h2> <p>在开发中,我们常常需要ViewPager结合Fragment一起使用,来实现多页签的切换效果。在以前,我们有 PagerSlidingTabStrip 、 SmartTabLayout 、 FlycoTabLayout 、 ViewPagerIndicator 等一系列第三方库来帮我们实现。</p> <p>而现在,我们可以使用 Design support library 库的 TabLayout 来实现了。</p> <h2><strong>二、最终效果图</strong></h2> <p style="text-align:center"><img src="https://simg.open-open.com/show/35e8408a8e2f059eb3d2ff98d69fdb8f.gif"></p> <h2><strong>三、TabLayout的使用</strong></h2> <h3><strong>1. 添加依赖</strong></h3> <p>由于TabLayout在design包内,所以首先需要在app目录下的 build.gradle 中添加以下依赖:</p> <pre> <code class="language-java">dependencies { ... compile 'com.android.support:design:23.4.0' }</code></pre> <h3><strong>2. 创建布局</strong></h3> <p>布局相当简单,只要添加TabLayout和ViewPager的布局即可:</p> <h3>layout/activity_main.xml</h3> <pre> <code class="language-java"><?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:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" style="@style/TabLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" /> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@android:color/white"/> </LinearLayout></code></pre> <p>还有其他的属性我习惯在style文件中设置:</p> <h3>values/styles.xml</h3> <pre> <code class="language-java"><!-- TabLayout样式 --> <style name="TabLayoutStyle" parent="Widget.Design.TabLayout"> <item name="tabIndicatorColor">@color/colorPrimary</item> <item name="tabSelectedTextColor">@color/colorPrimary</item> <item name="tabTextAppearance">@style/TabTextAppearence</item> <item name="tabPaddingEnd">0dp</item> </style> <style name="TabTextAppearence" parent="TextAppearance.Design.Tab"> <item name="android:textSize">16sp</item> <item name="textAllCaps">false</item> </style></code></pre> <h3><strong>3. 创建Fragment</strong></h3> <pre> <code class="language-java">package com.sherlockshi.badgedtablayoutpractise; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Author: SherlockShi * Date: 2016-11-01 16:31 * Description: */ public class PageFragment extends Fragment { private static final String PAGE_NAME_KEY = "PAGE_NAME_KEY"; public static PageFragment getInstance(String pageName) { Bundle args = new Bundle(); args.putString(PAGE_NAME_KEY, pageName); PageFragment pageFragment = new PageFragment(); pageFragment.setArguments(args); return pageFragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_page, container, false); TextView textView = (TextView) view.findViewById(R.id.tv_page_name); textView.setText(getArguments().getString(PAGE_NAME_KEY)); return view; } }</code></pre> <p>其中Fragment的布局 layout/fragment_page.xml :</p> <pre> <code class="language-java"><?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/tv_page_name" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"/></code></pre> <h3><strong>4. ViewPager的适配器</strong></h3> <pre> <code class="language-java">package com.sherlockshi.badgedtablayoutpractise; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.List; /** * Author: SherlockShi * Date: 2016-11-01 17:38 * Description: */ public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { private Context mContext; private List<Fragment> mFragmentList; private List<String> mPageTitleList; private List<Integer> mBadgeCountList; public SimpleFragmentPagerAdapter(Context context, FragmentManager fm, List<Fragment> fragmentList, List<String> pageTitleList, List<Integer> badgeCountList) { super(fm); this.mContext = context; this.mFragmentList = fragmentList; this.mPageTitleList = pageTitleList; this.mBadgeCountList = badgeCountList; } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return mPageTitleList.get(position); } }</code></pre> <h3><strong>5. 设置TabLayout</strong></h3> <pre> <code class="language-java">package com.sherlockshi.badgedtablayoutpractise; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List<String> mPageTitleList = new ArrayList<String>(); private List<Fragment> mFragmentList = new ArrayList<Fragment>(); private List<Integer> mBadgeCountList = new ArrayList<Integer>(); private SimpleFragmentPagerAdapter mPagerAdapter; private TabLayout mTabLayout; private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initFragments(); initView(); } private void initFragments() { mPageTitleList.add("Tab1"); mPageTitleList.add("Tab2"); mPageTitleList.add("Tab3"); mBadgeCountList.add(6); mBadgeCountList.add(16); mBadgeCountList.add(166); for (int i = 0; i < mPageTitleList.size(); i++) { mFragmentList.add(PageFragment.getInstance(mPageTitleList.get(i))); } } private void initView() { mTabLayout = (TabLayout) findViewById(R.id.tab_layout); mViewPager = (ViewPager) findViewById(R.id.view_pager); mPagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList, mPageTitleList); mViewPager.setAdapter(mPagerAdapter); mTabLayout.setupWithViewPager(mViewPager); initBadgeViews(); setUpTabBadge(); } }</code></pre> <h2><strong>四、设置角标</strong></h2> <h3><strong>1. 添加角标Badge</strong></h3> <p>添加角标的关键代码只需要一行:</p> <pre> <code class="language-java">mBadgeViews.get(i).setTargetView(((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i));</code></pre> <p>完整代码只需要在设置完TabLayout和ViewPager后,遍历每一个Tab,为Tab添加角标:</p> <pre> <code class="language-java">private void setUpTabBadge() { for (int i = 0; i < mFragmentList.size(); i++) { mBadgeViews.get(i).setTargetView(((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i)); mBadgeViews.get(i).setText(formatBadgeNumber(mBadgeCountList.get(i))); } }</code></pre> <h3><strong>2. 更新角标</strong></h3> <p>在需要更新角标的地方,只要调用以下方法就可实现:</p> <pre> <code class="language-java">mBadgeCountList.set(1, count++); setUpTabBadge();</code></pre> <p>以上,就可以轻松地为TabLayout添加角标,并处理角标的更新了。</p> <h2><strong>五、问题</strong></h2> <h3><strong>1. 重复选中的状态</strong></h3> <p>但是如果需要更新角标,那么在 更新角标后 ,再点击另一个Tab,会出现 上一个Tab 和 当前Tab 都是选中状态(如下图的Tab1和Tab2):</p> <p style="text-align:center"><img src="https://simg.open-open.com/show/e22a18819d0202973ddff6279d329ea0.png"></p> <h3><strong>2. 角标位置不可控</strong></h3> <p>而且如上图所示,角标的位置不好控制,有的离文字很近,有的离得很远,无法精确控制。</p> <h2><strong>六、最实用的TabLayout加角标方法</strong></h2> <h3><strong>1. 添加getTabItemView()方法</strong></h3> <p>在重写的FragmentPagerAdapter中添加自定义Tab布局方法:</p> <pre> <code class="language-java">public View getTabItemView(int position) { View view = LayoutInflater.from(mContext).inflate(R.layout.tab_layout_item, null); TextView textView = (TextView) view.findViewById(R.id.textview); textView.setText(mPageTitleList.get(position)); View target = view.findViewById(R.id.badgeview_target); BadgeView badgeView = new BadgeView(mContext); badgeView.setTargetView(target); badgeView.setBadgeMargin(0, 6, 10, 0); badgeView.setTextSize(10); badgeView.setText(formatBadgeNumber(mBadgeCountList.get(position))); return view; }</code></pre> <p>对应的自定义布局为:</p> <pre> <code class="language-java"><?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="wrap_content" android:orientation="horizontal"> <!-- LinearLayout的Height必须为wrap_content,如果为match_parent,那么在第二次加载Badge的时候,Tab布局会出现问题 --> <View android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"/> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginLeft="-30dp" android:textColor="@color/tab_text_color_selector"/> <View android:id="@+id/badgeview_target" android:layout_width="0dp" android:layout_weight="1" android:layout_height="40dp" android:layout_marginLeft="4dp" android:layout_gravity="center"/> </LinearLayout></code></pre> <h3><strong>2. 设置自定义布局</strong></h3> <pre> <code class="language-java">private void setUpTabBadge() { for (int i = 0; i < mFragmentList.size(); i++) { TabLayout.Tab tab = mTabLayout.getTabAt(i); // 更新Badge前,先remove原来的customView,否则Badge无法更新 View customView = tab.getCustomView(); if (customView != null) { ViewParent parent = customView.getParent(); if (parent != null) { ((ViewGroup) parent).removeView(customView); } } // 更新CustomView tab.setCustomView(mPagerAdapter.getTabItemView(i)); } // 需加上以下代码,不然会出现更新Tab角标后,选中的Tab字体颜色不是选中状态的颜色 mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(true); }</code></pre> <p>上面的示例会有两个坑:</p> <ul> <li>一个坑是每次为TabLayout添加Badge后,会出现Tab的字体颜色不是选中状态的颜色,需要手动设置Tab为选中状态,可以参考上面的第19行代码解决,这应该是TabLayout的一个Bug;</li> <li>另一个坑是如果每次更新Badge的时候,直接重新tab.setCustomView的话,会出现Badge不更新,解决办法是先移除之前的自定义布局,然后再重新设置布局,具体可参考第6-12行代码解决。</li> </ul> <h2><strong>七、总结</strong></h2> <p>以上是自己在使用TabLayout的过程中发现的一些问题及解决办法,如果大家有更好的解决方法,或者还有别的坑,欢迎留言。</p> <p>当然,大家也可以直接使用第三方控件来实现以上功能,现在主流的几个控件也都做得很好,也很省心。</p> <h2><strong>八、参考资料</strong></h2> <p><a href="/misc/goto?guid=4959723680949682777" rel="nofollow,noindex">android design library提供的TabLayout的用法</a></p> <p><a href="/misc/goto?guid=4959723681052827775" rel="nofollow,noindex">Google Play Style Tabs using TabLayout</a></p> <p><a href="/misc/goto?guid=4959723681141827536" rel="nofollow,noindex">Android Tablayout tabs with notification badge like whatsApp</a></p> <p><br> </p>