5

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.

Vrangle
  • 323
  • 5
  • 13

1 Answers1

5

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);
DEIONaLiMs
  • 162
  • 1
  • 11
  • I tried this way, but is this a efficient way to do it? – Vrangle Jul 09 '15 at 20:39
  • After setting the View when I try to alter the name of the tabs from MainActivity I'm getting this error 'void android.view.View.unFocus(android.view.View)' on a null object reference – Vrangle Jul 09 '15 at 21:17
  • 1
    You can't access tabs customViews after setting them. On the next design support library release we will be able to do so with tab.getCustomView(). This method exists but is private for now. – DEIONaLiMs Jul 13 '15 at 13:51
  • As DEIONaLiMs stated that tab.getCustomView() has been added with the support library release 23.0.0. – Ray Hunter Aug 27 '15 at 20:36