Tablayout更新自定义视图选项卡的页面标题

5
我制作了一个选项卡布局,并为选项卡设置了自定义布局。有时我想更改这些选项卡的标题,但我不知道正确的方法,请帮帮我。
我的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> 

并且在 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");

无法正常工作,请帮助我更新自定义选项卡的TextView。
1个回答

5

您需要先填充视图。

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);

我尝试了这种方法,但这是一种高效的方式吗? - Vrangle
在设置视图后,当我尝试从MainActivity更改选项卡的名称时,我会收到此错误“void android.view.View.unFocus(android.view.View)”关于空对象引用。 - Vrangle
1
在设置选项卡自定义视图后,您无法访问选项卡customViews。在下一个设计支持库的发布中,我们将能够通过tab.getCustomView()这个方法来做到这一点。这种方法已经存在,但现在是私有的。 - DEIONaLiMs
正如DEIONaLiMs所述,tab.getCustomView()已经在支持库版本23.0.0中添加。 - Ray Hunter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接