获取TabLayout选项卡的textview

apo*_*low 8 tabs android material-design android-tablayout

我想以编程方式更改选项卡的textview.有没有办法做到这一点?

有关旧TabHost视图的答案,我正在使用Google的Material Design库使用的TabLayout android.support.design.widget.TabLayout.

对于TabHost: 如何将填充添加到选项卡标签?

Lav*_*wal 14

这是有效的解决方案

int wantedTabIndex = 0;
TextView tv = (TextView)(((LinearLayout)((LinearLayout)mTabLayout.getChildAt(0)).getChildAt(wantedTabIndex)).getChildAt(1));
tv.setText("Hello world!");
Run Code Online (Sandbox Code Playgroud)

只需更改最后一个索引 一,现在上面的代码将起作用

删除了崩溃

java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.TextView
Run Code Online (Sandbox Code Playgroud)


apo*_*low 5

使用给定的标签:

 int wantedTabIndex = 0;
 TextView tv = (TextView)(((LinearLayout)((LinearLayout)mTabLayout.getChildAt(0)).getChildAt(wantedTabIndex)).getChildAt(0));
 tv.setText("Hello world!");
Run Code Online (Sandbox Code Playgroud)

  • 这会因 `java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.TextView` in support lib `22.2.1` 而崩溃 (2认同)

Kev*_*vin 5

    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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

将您的 TabLayout 传递给此递归方法。它将找到任何属于 TextView 的子项并将其全部大写模式设置为关闭。避免所有其他非常具体的类型转换。如果它似乎不起作用,请稍后在您的代码中调用它。我在 onCreate 中有它,但这不起作用。稍后在代码中调用它,它工作得很好。

影响所有标签,不仅仅是一个,但我认为这是最常见的用法。也不是特定于 TabLayout。可用于包含要更改的 TextViews 的任何布局。