自定义Tablayout标题布局

转载:https://blog.csdn.net/qiao0809/article/details/53506008

首先是自己需要的布局

<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/tv_tablayout"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="来啊"
    android:textColor="@drawable/text_color_tablayout"
    android:gravity="center"
    android:textSize="36px"
    android:drawableRight="@drawable/image_tablayout"
    android:drawablePadding="14px"

    />
</com.zhy.autolayout.AutoLinearLayout>

然后是根据选择状态切换的图片和字体颜色设置:text_color_tablayout字体颜色

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 没有焦点时字体颜色 -->
    <item
        android:state_selected="false"
        android:color="@color/tablayout_tv_no"/>
    <!--选中时的字体颜色  -->
    <item
        android:state_selected="true"
        android:color="@color/tablayout_tv"/>
    <!-- 非触摸模式下获得焦点并单击时的字体颜色 -->
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:color="@color/tablayout_tv"/>
</selector>

图片的设置:image_tablayout

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 没有焦点时字体颜色 -->
    <item
        android:state_selected="false"
        android:drawable="@drawable/record_hui"/>
    <!--选中时的字体颜色  -->
    <item
        android:state_selected="true"
       android:drawable="@drawable/record_lan"/>
    <!-- 非触摸模式下获得焦点并单击时的字体颜色 -->
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/record_lan"/>
</selector>

自定义的标题有了,图片切换和字体颜色的切换也有了,然后就是设置:

for (int i = 0; i < adapter.getCount(); i++) {
    TabLayout.Tab tab = tablayout.getTabAt(i);//获得每一个tab
     tab.setCustomView(R.layout.tabayout_record);//给每一个tab设置view
     if (i == 0) {
         // 设置第一个tab的TextView是被选择的样式
          tab.getCustomView().findViewById(R.id.tv_tablayout).setSelected(true);
         //第一个tab被选中
          }
    TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tv_tablayout);
    textView.setText(titles[i]);//设置tab上的文字
     }
tablayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        tab.getCustomView().findViewById(R.id.tv_tablayout).setSelected(true);
        mvp_record.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});

这样一个自定义的tablayout就完成了。

猜你喜欢

转载自blog.csdn.net/Liu_ser/article/details/83857821