Android Tablayout 自定义Tab布局的使用

开发公司的项目中需要实现以下效果图,需要自定义TabLayout 中的Tab

Tablayout xml

 "@+id/dialog_mod_icon_tablayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:tabIndicatorHeight="0dp"
        android:paddingLeft="@dimen/commom_margin_20"
        app:tabMode="scrollable"
        app:tabPaddingStart="@dimen/commom_margin_5"
        app:tabPaddingEnd="@dimen/commom_margin_5"
      app:tabSelectedTextColor="@color/common_tv_dark_red" />

其中如果多个tab 需要滚动则要设置app:tabMode="scrollable",对于tabPaddingStarttabPaddingEnd则是设置Tab 的左边和右边padding,根据具体的需求来设置就好,这里如果没有设置,TabLayout 或自动设置一个默认的值給Tab,

setCustomView()

设置自定义的Tab布局給Tablayout

 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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/choose_icon_tab_tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@drawable/selector_icon_choose_txt_bg"
        android:padding="@dimen/commom_margin_4"
        android:textSize="@dimen/commom_tv_size_12"
        android:textStyle="bold" />
LinearLayout>

selector_icon_choose_txt_bg


<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


<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="@dimen/commom_margin_2"/>
    <stroke android:color="@color/common_bg_dali_gray_cc4" android:width="1dp"/>
shape>

shape_icon_choose_no_select


<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="@dimen/commom_margin_2"/>

    <stroke android:color="@color/common_bg_dali_gray_62" android:width="1dp"/>
shape>

通过以上设置,就实现了我图中TabLayout 的子Tab的布局。。

Android—Tablayout自定义Tab的背景和字体的颜色变化

你可能感兴趣的:(Android)