Android在Fragment中使用Tab

Tab使用非常常见,实现方式也很多,这里分享一种使用ViewPagerIndicator快速实现tab的方法,并且可以根据需要实现不同的效果,包括文字title、文字title+图标、小点指示灯,并可以实现滑动自动切换标签效果。
来张效果截图:
Android在Fragment中使用Tab_第1张图片

添加tab步骤如下:
1、添加使用ViewPagerIndicator库(AS中直接导入library)
2、Fragment布局文件fragment.xml中添加
<com.viewpagerindicator.TabPageIndicator
    android:id="@+id/indicator"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    />

<android.support.v4.view.ViewPager
    android:id="@+id/fragmentviewpager"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1" />
3、fragment中加载xml文件,并使用库中包含的style
在OnCreateView函数中添加
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

View view = localInflater.inflate(R.layout.activity_order, null);
initView(view);
initData();
return view;
initView函数如下:
private void initView(View view){
    mViewPager = (ViewPager) view.findViewById(R.id.fragmentviewpager);
    mIndicator = (TabPageIndicator) view.findViewById(R.id.indicator);
}
initData函数如下:
private void initData() {
    FragmentManager mFm = getChildFragmentManager();
    List<Fragment> fragments = new ArrayList<Fragment>();
    fragments.add(Fragment1.getInstance());
    fragments.add(Fragment2.getInstance());
    fragments.add(Fragment3.getInstance());
    MyAdapter mAdapter = new MyAdapter(mFm, fragments, getActivity());
    mViewPager.setAdapter(mAdapter);
    mIndicator.setViewPager(mViewPager);
}
4、覆写Adapter
class MyAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;  private Context context;  private static final int[] CONTENT = {R.string.home, R.string.message, R.string.me};

    private String getContent(int resId) {
        return context.getString(resId);
    }

    public OrderAdapter(FragmentManager fm, List<Fragment> fragments, Context context) {
        super(fm);
        this.fragments = fragments;
        this.context = context;
    }

    @Override
    public Fragment getItem(int arg0) {
        return fragments.get(arg0);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return getContent(CONTENT[position]);
    }

}

字体颜色更改方法:
1、在drawable中添加tab_color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_selected="true" android:color="#f9a202"></item>
    <item android:state_selected="false" android:color="#000000"></item>

</selector>
2、在对应的sytle下(如使用TabPage,修改CustomTabPageIndicator)更改
 
  
<item name="android:textColor">@drawable/tab_color_selector</item>
备注:如果将xml文件放在color目录下,对应的style设置为@color/tab_color_selector
 
  

你可能感兴趣的:(android,tab,Fragment)