一、前言
在開發(fā)中,我們常常需要ViewPager結(jié)合Fragment一起使用邓馒,來實(shí)現(xiàn)多頁簽的切換效果。在以前蛾坯,我們有以下一系列第三方庫來幫我們實(shí)現(xiàn):
而現(xiàn)在光酣,我們可以使用Design support library
庫的TabLayout
來實(shí)現(xiàn)了。
二脉课、最終效果圖
三救军、TabLayout的使用
1. 添加依賴
由于TabLayout在design包內(nèi),所以首先需要在app目錄下的build.gradle
中添加以下依賴:
dependencies {
...
compile 'com.android.support:design:23.4.0'
}
2. 創(chuàng)建布局
布局相當(dāng)簡(jiǎn)單倘零,只要添加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>
還有其他的屬性我習(xí)慣在style文件中設(shè)置:
values/styles.xml
<!-- 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>
3. 創(chuàng)建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<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);
}
}
5. 設(shè)置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<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();
}
}
四缤言、設(shè)置角標(biāo)
1. 添加角標(biāo)Badge
添加角標(biāo)的關(guān)鍵代碼只需要一行:
mBadgeViews.get(i).setTargetView(((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i));
完整代碼只需要在設(shè)置完TabLayout和ViewPager后,遍歷每一個(gè)Tab视事,為Tab添加角標(biāo):
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. 更新角標(biāo)
在需要更新角標(biāo)的地方胆萧,只要調(diào)用以下方法就可實(shí)現(xiàn):
mBadgeCountList.set(1, count++);
setUpTabBadge();
以上,就可以輕松地為TabLayout添加角標(biāo)俐东,并處理角標(biāo)的更新了跌穗。
五、問題
1. 重復(fù)選中的狀態(tài)
但是如果需要更新角標(biāo)虏辫,那么在更新角標(biāo)后
蚌吸,再點(diǎn)擊另一個(gè)Tab,會(huì)出現(xiàn)上一個(gè)Tab
和當(dāng)前Tab
都是選中狀態(tài)(如下圖的Tab1和Tab2):
2. 角標(biāo)位置不可控
而且如上圖所示砌庄,角標(biāo)的位置不好控制羹唠,有的離文字很近,有的離得很遠(yuǎn)娄昆,無法精確控制佩微。
六、最實(shí)用的TabLayout加角標(biāo)方法
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;
}
對(duì)應(yīng)的自定義布局為:
<?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的時(shí)候,Tab布局會(huì)出現(xiàn)問題 -->
<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>
2. 設(shè)置自定義布局
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));
}
// 需加上以下代碼,不然會(huì)出現(xiàn)更新Tab角標(biāo)后,選中的Tab字體顏色不是選中狀態(tài)的顏色
mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(true);
}
上面的示例會(huì)有兩個(gè)坑:
- 一個(gè)坑是每次為TabLayout添加Badge后萌焰,會(huì)出現(xiàn)Tab的字體顏色不是選中狀態(tài)的顏色哺眯,需要手動(dòng)設(shè)置Tab為選中狀態(tài),可以參考上面的第19行代碼解決扒俯,這應(yīng)該是TabLayout的一個(gè)Bug奶卓;
- 另一個(gè)坑是如果每次更新Badge的時(shí)候一疯,直接重新tab.setCustomView的話,會(huì)出現(xiàn)Badge不更新夺姑,解決辦法是先移除之前的自定義布局墩邀,然后再重新設(shè)置布局,具體可參考第6-12行代碼解決盏浙。
七磕蒲、總結(jié)
以上是自己在使用TabLayout的過程中發(fā)現(xiàn)的一些問題及解決辦法,如果大家有更好的解決方法只盹,或者還有別的坑辣往,歡迎留言。
當(dāng)然殖卑,大家也可以直接使用第三方控件來實(shí)現(xiàn)以上功能站削,現(xiàn)在主流的幾個(gè)控件也都做得很好,也很省心孵稽。
項(xiàng)目代碼已共享到Github:BadgedTabLayoutPractise
八许起、參考資料
android design library提供的TabLayout的用法
Google Play Style Tabs using TabLayout
Android Tablayout tabs with notification badge like whatsApp
PS:歡迎關(guān)注SherlockShi博客