Android 中TabLayout实现Tab自定义和选中文字加粗

来源:互联网 发布:托勒密王朝 知乎 编辑:程序博客网 时间:2024/06/06 05:43

在Android开发当中,我们几乎都得用到TabLayout+Fragment来实现信息的展示,但是,很多时候我们的需要又很不同,

TabLayout的基本使用推荐以下文章:http://www.jianshu.com/p/2b2bb6be83a8

需求一:自定义TabLayout中Tab的布局

这里写图片描述

这里我们使用到是不同与TabLayout的默认布局,这样的话,需要什么样的样式都可以自己实现。
1.实现这样的效果主要是在添加Tab时,我们使用自定义的布局

    private void addCustomTab(List<GetIconBean.IconListBean.CategoryBean> listData, int i) {        TabLayout.Tab tab = tabLayout.newTab();        //加载自定义的布局        View view = LayoutInflater.from(context).inflate(R.layout.widget_choose_icon_tab_bg, null);        TextView tv = (TextView) view.findViewById(R.id.choose_icon_tab_tv);        tv.setText(listData.get(i).getName());        tab.setCustomView(view);        tabLayout.addTab(tab);    }
  • widget_choose_icon_tab_bg.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:id="@+id/choose_icon_tab_tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:padding="2dp"        android:background="@drawable/selector_icon_choose_txt_bg" /></LinearLayout>
  • selector_icon_choose_txt_bg.xml

         文字选中与未选中的selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/shape_icon_choose_select" android:state_checked="true" />    <item android:drawable="@drawable/shape_icon_choose_select" android:state_selected="true" />    <item android:drawable="@drawable/shape_icon_choose_no_select" /></selector>
  • shape_icon_choose_select.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="@color/line_gray"/>    <stroke android:color="@color/tv_black" android:width="1dp"/></shape>
  • shape_icon_choose_select.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">    <stroke android:color="@color/tv_black" android:width="1dp"/></shape>

当然也可以自己实现任何布局,例如文字左边添加图片……

需求二:TabLayout选中文字加粗

这里写图片描述

这里实际上是有一个库,对TabLayout进行了封装,使用和TabLayout几乎相同,使用很简单
文章地址:http://blog.csdn.net/a1533588867/article/details/53810409
github:https://github.com/AndroidKun/XTabLayout