Search code examples
androidandroid-tablayoutandroid-tabs

Increase width custom view on tab in tablayout


I currently have a tablayout with a custom tab. Currently the tabs display great the only issue is that the tabs seem to be confined to the tablayout tab size leaving a space in between the next tab. Is there a way to make the custom view on the tab match the tablayouts tab size? Please let me know.

custom_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    textview element

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

TabLayout tabLayout = findViewById(R.id.tabLayout);
        new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setCustomView(R.layout.custom_tab);
                //get textview and set custom text
                //set background color
            }
        }).attach();

Solution

  • After some digging I was able to find an answer. The problem is when using a custom view, the tablayout inflates the view to a maximum width and height. The best way to add a background that fully matches the full tablayout tab width and height is to use the tablayout xml tabBackground and add a drawable that includes a selector plus the textColor and textSelectedColor. Follow this tutorial for more information: https://www.thecodecity.com/2016/12/changing-background-color-of-tab.html#:~:text=%20How%20to%20change%20tab%20color%20in%20TabLayout,create%20as%20the%20background%20of%20the...%20More%20