原文: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一起使用,来实现多页签的切换效果。在以前,我们有以下一系列第三方库来帮我们实现:
而现在,我们可以使用Design support library
库的TabLayout
来实现了。
由于TabLayout在design包内,所以首先需要在app目录下的build.gradle
中添加以下依赖:
dependencies {
...
compile 'com.android.support:design:23.4.0'
}
布局相当简单,只要添加TabLayout和ViewPager的布局即可:
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文件中设置:
<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>
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"/>
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);
}
}
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();
}
}
添加角标的关键代码只需要一行:
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)));
}
}
在需要更新角标的地方,只要调用以下方法就可实现:
mBadgeCountList.set(1, count++);
setUpTabBadge();
以上,就可以轻松地为TabLayout添加角标,并处理角标的更新了。
但是如果需要更新角标,那么在更新角标后
,再点击另一个Tab,会出现上一个Tab
和当前Tab
都是选中状态(如下图的Tab1和Tab2):
而且如上图所示,角标的位置不好控制,有的离文字很近,有的离得很远,无法精确控制。
在重写的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"/>
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的过程中发现的一些问题及解决办法,如果大家有更好的解决方法,或者还有别的坑,欢迎留言。
当然,大家也可以直接使用第三方控件来实现以上功能,现在主流的几个控件也都做得很好,也很省心。
项目代码已共享到Github:BadgedTabLayoutPractise
android design library提供的TabLayout的用法
Google Play Style Tabs using TabLayout
Android Tablayout tabs with notification badge like whatsApp