美文网首页安卓文档
android TabLayout使用小结

android TabLayout使用小结

作者: Zc0716 | 来源:发表于2018-03-24 18:07 被阅读0次

一、简介

Tablayout是Google官方在2014年I/O大会上推出的全新设计语言——Material Design中的一个控件。方便开发者处理横向的tab页中镶嵌viewpager的场景。

二、具体使用

1、在应用的build.gradle中添加support.design库支持(版本需和v7版本相同)

implementation 'com.android.support:design:26.1.0'

2、布局文件中添加tablayout控件及viewpager

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            app:tabIndicatorColor="#f00"
            app:tabMode="fixed"
            app:tabIndicatorHeight="0dp"
            app:tabTextAppearance="@style/tabLayoutStyle"/>
        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>

3、创建每个tab对应显示的Fragment(推荐使用工厂模式)

public class FragmentFactory {
    public static HashMap<Integer,BaseFragment> baseFragments =new HashMap<>();
    public static BaseFragment createFragment(int position){
        BaseFragment baseFragment;
        switch (position){
            case 0:
                baseFragment=new NormalFragment();
                Bundle args =new Bundle();
                args.putString("title","首页");
                baseFragment.setArguments(args);
                baseFragments.put(position,baseFragment);
            break;
            case 1:
                baseFragment=new NormalFragment();
                Bundle args1 =new Bundle();
                args1.putString("title","新闻");
                baseFragment.setArguments(args1);
                baseFragments.put(position,baseFragment);
            break;
            case 2:
                baseFragment=new NormalFragment();
                Bundle args2 =new Bundle();
                args2.putString("title","娱乐");
                baseFragment.setArguments(args2);
                baseFragments.put(position,baseFragment);
            break;
            case 3:
                baseFragment=new NormalFragment();
                Bundle args3 =new Bundle();
                args3.putString("title","音乐");
                baseFragment.setArguments(args3);
                baseFragments.put(position,baseFragment);
            break;
            default:
                break;

        }
        return baseFragments.get(position);
    }
}

public abstract class BaseFragment extends Fragment{
    public Context mContext;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=getContext();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadData();
    }

    protected abstract void loadData();

    protected abstract View initView();

}

public class NormalFragment extends BaseFragment{

    @Override
    protected void loadData() {

    }

    @Override
    protected View initView() {
        TextView textView =new TextView(mContext);
        String title=getArguments().getString("title");
        textView.setText(title);
        textView.setTextColor(Color.BLACK);
        textView.setTextSize(18);
        textView.setGravity(Gravity.CENTER);
        return textView;
    }
}

4、定义viewpager的适配器,继承FragmentPagerAdapter

 public class TabAdapter extends FragmentPagerAdapter{
        public String[] mTitles;
        public int[] mIcons;
        public TabAdapter(FragmentManager fm) {
            super(fm);
            mTitles=getResources().getStringArray(R.array.tab_short_Title);
            mIcons= new int[]{R.mipmap.ic_launcher_round, R.mipmap.location_icon, R.mipmap.home_msg_ic, R.mipmap.ic_launcher_round};
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.[position];
        }

        @Override
        public Fragment getItem(int position) {
            return FragmentFactory.createFragment(position);
        }

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

5、设置viewpager的适配器,并关联tablayout与viewpager

viewPager.setAdapter(tabAdapter);
tableLayout.setupWithViewPager(viewPager);

三、TabLayout样式

1、某些情况下我们需要修改tablayout的文字的字体大小、颜色,指示器的显示厚度,整个TabLayout的背景颜色等等,此时我们可以自定义TabLayout的style并引入即可

<style name="myTabLayout" parent="Widget.Design.TabLayout">
        <item name="tabMaxWidth">@dimen/tab_max_width</item>
        <item name="tabIndicatorColor">?attr/colorAccent</item>
        <item name="tabIndicatorHeight">2dp</item>
        <item name="tabPaddingStart">12dp</item>
        <item name="tabPaddingEnd">12dp</item>
        <item name="tabBackground">?attr/selectableItemBackground</item>
        <item name="tabTextAppearance">@style/tabLayoutStyle</item>
        <item name="tabSelectedTextColor">?android:textColorPrimary</item>
    </style>
<style name="tabLayoutStyle"parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">?android:textColorSecondary</item>
    </style>

2、原生的tablayout上显示的仅仅是文字,当我们需要将文字替换成图片时,可以尝试将图片转换成SpannableString 返回,并将Layout的textAllCaps(属性默认值是true,会阻止ImageSpan的渲染)重写为false即可(注:xml中需要引用app:tabTextAppearance="@style/tabLayoutStyle")

 @Override
public CharSequence getPageTitle(int position) {
  Drawable drawable = ContextCompat.getDrawable(MainActivity.this,mIcons[position]);
  drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
  ImageSpan imageSpan =new ImageSpan(drawable,ImageSpan.ALIGN_BOTTOM);
  SpannableString spannableString =new SpannableString(" ");
  spannableString.setSpan(imageSpan,0,1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  return spannableString ;
}

 <style name="tabLayoutStyle" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">?android:textColorSecondary</item>
        <item name="textAllCaps">false</item>
</style>

3、若tab标签为一个复杂的布局,常规的文字和图片无法满足需求,这时候我们就需要进行自定义布局

//1、重写getPageTitle方法返回null,并在adapter中定义返回的view
@Override
public CharSequence getPageTitle(int position) {
  return null;
 }

public View getTabView(int position){
  View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_tab,null);
  TextView textView=view.findViewById(R.id.tv_tab);
  ImageView imageView=view.findViewById(R.id.iv_tab);
  textView.setText(mTitles[position]);
  imageView.setImageResource(mIcons[position]);
  if (position ==tableLayout.getSelectedTabPosition()){
    textView.setTextColor(Color.RED);
  }else {
    textView.setTextColor(Color.GREEN);
 }
  return view;
}

//2、遍历设置对应的tabview,并监听tab切换时状态颜色的改变
TabAdapter tabAdapter=new TabAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabAdapter);
tableLayout.setupWithViewPager(viewPager);
int tabCount=tableLayout.getTabCount();
for (int i=0;i<tabCount;i++){
  tableLayout.getTabAt(i).setCustomView(tabAdapter.getTabView(i));
}
View view1 = tableLayout.getChildAt(0);
view1.setBackgroundDrawable(new ProxyDrawable(view1));
tableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
  @Override
  public void onTabSelected(TabLayout.Tab tab) {
    TextView tabText = tab.getCustomView().findViewById(R.id.tv_tab);
    tabText.setTextColor(Color.RED);
  }
  @Override
  public void onTabUnselected(TabLayout.Tab tab) {
    TextView tabText = tab.getCustomView().findViewById(R.id.tv_tab);
    tabText.setTextColor(Color.GREEN);
  }
  @Override
  public void onTabReselected(TabLayout.Tab tab) {
  }
});

相关文章

网友评论

    本文标题:android TabLayout使用小结

    本文链接:https://www.haomeiwen.com/subject/ubtccftx.html