简体   繁体   中英

Customize the selected tab in TabLayout

Here's what I need

在此处输入图片说明

Here's what I achieved ( Ignore the size and background color )

在此处输入图片说明

My codes:

<android.support.design.widget.TabLayout
                    android:id="@+id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    app:tabMode="fixed"
                    app:tabBackground="@drawable/tab_selector"
                    app:tabIndicatorHeight="0dp"
                    app:tabTextAppearance="?android:textAppearanceMedium"
                    app:tabSelectedTextColor="#6e00b5"/>

tab_selector.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/selected_dot"
        android:state_selected="true"/>

</selector>

selected_dot.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape
        android:innerRadius="0dp"
        android:shape="ring"
        android:thickness="4dp"
        android:useLevel="false">
        <solid android:color="#6e00b5"/>
    </shape>
</item>

The only problem I'm facing is to place the dot under the text.

Simple Solution

Use app:tabIndicator instead of app:tabBackground

<TabLayout
    app:tabIndicator="@drawable/tab_dot"
    app:tabIndicatorHeight="8dp">

Note that use at least double app:tabIndicatorHeight of tab thinkness ( 4dp ) to make that fully visible.

I don't think so, tab selector will work in case of tablayout . You need to implement in your own way

You need to set TabSlected listener and then add below code,

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
    @Override
    public void onTabSelected(TabLayout.Tab tab){
    int position = tab.getPosition();
    LinearLayout view = (LinearLayout) tabLayout.getChildAt(0);      
    TextView textView = (TextView) view.getChildAt(position);
//Below line will change selected tab textview title only.
    textView.setCompoundDrawablesWithIntrinsicBounds(null,null,null,objContext.getResources().getDrawable(R.drawable.selected_dot))
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM