Search code examples
android-fragmentsandroid-activityandroid-tabsandroid-tablelayoutandroid-design-library

Tablayout update page title of custom view tabs


I made a tablayout tabs, which has custom layout for tabs, Sometimes I wish to change the title of those tabs. but I don't get right way of doing it, kindly help me.

my custom_tab.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/titttle"
        android:textStyle="bold"
        android:text="MYTITLE"
        android:paddingLeft="10dp"/>

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/count"
        android:textStyle="bold"
        android:text="1"
        android:paddingLeft="10dp"/>

</RelativeLayout> 

and in MainActivity.java

tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
 tabLayout.getTabAt(0).setCustomView(R.layout.tab_custom_view);
 tabLayout.getTabAt(1).setCustomView(R.layout.tab_custom_view);
TextView textView = (TextView)tabLayout.getChildAt(1).getRootView().findViewById(R.id.titttle);
textView.setText("New Title");

here

TextView textView = (TextView)tabLayout.getChildAt(1).getRootView().findViewById(R.id.titttle);
    textView.setText("New Title");

is not working, help me out to update the custom tab's textview.


Solution

  • You need to inflate the view first.

    View v = View.inflate(context, R.layout.tab_custom_view, null);
    Text textView = (TextView) v.findViewById(R.id.titttle);
    textView.setTitle("New Title");
    tabLayout.getTabAt(0).setCustomView(v);