为TabLayout添加角标的最简单方法

原文:http://sherlockshi.github.io/2016/11/02/15_Android/1510_View/TabLayout/%E4%B8%BATabLayout%E6%B7%BB%E5%8A%A0%E8%A7%92%E6%A0%87%E7%9A%84%E6%9C%80%E7%AE%80%E5%8D%95%E6%96%B9%E6%B3%95/?utm_source=tuicool&utm_medium=referral

一、前言

在开发中,我们常常需要ViewPager结合Fragment一起使用,来实现多页签的切换效果。在以前,我们有以下一系列第三方库来帮我们实现:

  • PagerSlidingTabStrip
  • SmartTabLayout
  • FlycoTabLayout
  • ViewPagerIndicator
  • ...

而现在,我们可以使用Design support library库的TabLayout来实现了。

二、最终效果图

为TabLayout添加角标的最简单方法_第1张图片

三、TabLayout的使用

1. 添加依赖

由于TabLayout在design包内,所以首先需要在app目录下的build.gradle中添加以下依赖:

dependencies {
    ...
    compile 'com.android.support:design:23.4.0'
}

2. 创建布局

布局相当简单,只要添加TabLayout和ViewPager的布局即可:

layout/activity_main.xml

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>

还有其他的属性我习惯在style文件中设置:

values/styles.xml


    <style name="TabLayoutStyle" parent="Widget.Design.TabLayout">
        <item name="tabIndicatorColor">@color/colorPrimaryitem>
        <item name="tabSelectedTextColor">@color/colorPrimaryitem>
        <item name="tabTextAppearance">@style/TabTextAppearenceitem>
        <item name="tabPaddingEnd">0dpitem>
    style>
    <style name="TabTextAppearence" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">16spitem>
        <item name="textAllCaps">falseitem>
    style>

3. 创建Fragment

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;
    }
}

其中Fragment的布局layout/fragment_page.xml:

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"/>

4. ViewPager的适配器

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 mFragmentList;
    private List mPageTitleList;
    private List mBadgeCountList;

    public SimpleFragmentPagerAdapter(Context context,
                                      FragmentManager fm,
                                      List fragmentList,
                                      List pageTitleList,
                                      List 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);
    }
}

5. 设置TabLayout

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 mPageTitleList = new ArrayList();
    private List mFragmentList = new ArrayList();
    private List mBadgeCountList = new ArrayList();

    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();
    }
}

四、设置角标

1. 添加角标Badge

添加角标的关键代码只需要一行:

mBadgeViews.get(i).setTargetView(((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i));

完整代码只需要在设置完TabLayout和ViewPager后,遍历每一个Tab,为Tab添加角标:

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)));
    }
}

2. 更新角标

在需要更新角标的地方,只要调用以下方法就可实现:

mBadgeCountList.set(1, count++);
setUpTabBadge();

以上,就可以轻松地为TabLayout添加角标,并处理角标的更新了。

五、问题

1. 重复选中的状态

但是如果需要更新角标,那么在更新角标后,再点击另一个Tab,会出现上一个Tab当前Tab都是选中状态(如下图的Tab1和Tab2):

为TabLayout添加角标的最简单方法_第2张图片

2. 角标位置不可控

而且如上图所示,角标的位置不好控制,有的离文字很近,有的离得很远,无法精确控制。

六、最实用的TabLayout加角标方法

1. 添加getTabItemView()方法

在重写的FragmentPagerAdapter中添加自定义Tab布局方法:

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;
}

对应的自定义布局为:

"1.0" encoding="utf-8"?>
"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">
    

    "0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"/>

    "@+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"/>

    "@+id/badgeview_target"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="40dp"
        android:layout_marginLeft="4dp"
        android:layout_gravity="center"/>

2. 设置自定义布局

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);
}

上面的示例会有两个坑:

  • 一个坑是每次为TabLayout添加Badge后,会出现Tab的字体颜色不是选中状态的颜色,需要手动设置Tab为选中状态,可以参考上面的第19行代码解决,这应该是TabLayout的一个Bug;
  • 另一个坑是如果每次更新Badge的时候,直接重新tab.setCustomView的话,会出现Badge不更新,解决办法是先移除之前的自定义布局,然后再重新设置布局,具体可参考第6-12行代码解决。

七、总结

以上是自己在使用TabLayout的过程中发现的一些问题及解决办法,如果大家有更好的解决方法,或者还有别的坑,欢迎留言。

当然,大家也可以直接使用第三方控件来实现以上功能,现在主流的几个控件也都做得很好,也很省心。

项目代码已共享到Github:BadgedTabLayoutPractise

八、参考资料

android design library提供的TabLayout的用法

Google Play Style Tabs using TabLayout

Android Tablayout tabs with notification badge like whatsApp

你可能感兴趣的:(导航&&home)