Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the textview of the TabLayout's tab

I want to programmatically change a tab's textview. Is there any way to do this?

There are answers only concerning the old TabHost view, I am using the TabLayout used by Google's Material Design library using android.support.design.widget.TabLayout.

For TabHost: How to add padding to a tabs label?

like image 901
apollow Avatar asked Jul 08 '15 00:07

apollow


2 Answers

With a given tab:

 int wantedTabIndex = 0;
 TextView tv = (TextView)(((LinearLayout)((LinearLayout)mTabLayout.getChildAt(0)).getChildAt(wantedTabIndex)).getChildAt(0));
 tv.setText("Hello world!");
like image 178
apollow Avatar answered Sep 21 '22 07:09

apollow


    public static void setTextViewsCapsOff(View view) {
        if (!(view instanceof ViewGroup)) {
            return;
        }
        ViewGroup group = (ViewGroup)view;
        for (int i = 0; i < group.getChildCount(); i++) {
            View child = group.getChildAt(i);
            if (child instanceof TextView) {
                ((TextView)child).setAllCaps(false);
            } else {
                setTextViewsCapsOff(child);
            }
        }
    }

Pass in your TabLayout to this recursive method. It will find any child that is a TextView and set its All Caps mode off. Avoids all the other very specific typecasting. If it does not appear to work call it later in your code. I had it in onCreate but that did not work. Called it later in code and it worked perfectly.

Affects all Tabs, not just one but I figure this is the most common usage. Not specific to TabLayout either. Can be used for any layout that contains TextViews you want to change.

like image 31
Kevin Avatar answered Sep 22 '22 07:09

Kevin