4

我在 TabHost 中有一个带有 3 个选项卡的 Android 应用程序(文本标签,没有图像)。我这样设置标签:

intent = new Intent().setClass(this, AnnouncementsActivity.class);
spec = tabHost.newTabSpec("news").setIndicator("News").setContent(intent);
tabHost.addTab(spec);

我启动了一个后台线程以从我的服务器获取公告,并且我想更新选项卡上的文本标签以告诉用户有多少新公告。比如我想把Tab上的文字改成“新闻(3)”。如何访问和更改选项卡上的文本标签?

欢迎任何建议!

4

4 回答 4

5

你可以这样做

TabHost tabHost = getTabHost();
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);
tv.setText("New Tab Text");

System在哪里android.R.id.title生成,根据需要更改ChildIndexText即可

于 2013-08-18T02:28:37.977 回答
1

对于更高版本的android(5.1),这对我有用:

请注意,此示例仅更改第一个选项卡的文本。调整任意选项卡不会太难。

FragmentTabHost tabHost = (FragmentTabHost)view.findViewById(android.R.id.tabhost);
AppCompatTextView tv = null;
RelativeLayout parentLayout = (RelativeLayout)tabHost.getTabWidget().getChildAt(0);

for (int i = 0; i < parentLayout.getChildCount(); i++) {

    View tempView = parentLayout.getChildAt(i);

    if (tempView instanceof AppCompatTextView) {
        tv = (AppCompatTextView)tempView;
    }
}

if (tv != null) {
    tv.setText("Your updated text goes here");
}

我所做的只是通过调试器运行它并找出层次结构。我无法让 android.R.id.title 工作,因为文本视图现在由不同的 id 引用。无论如何,它现在也是 AppCompatTextView 而不是普通的旧 TextView。

同样,这不是最佳的,但对于较新版本的 android 可以获得所需的结果。

希望这可以帮助!

于 2016-06-14T20:57:16.170 回答
0

查看此处演示的代码,请参阅代码末尾有获取 textView 的 hacky 方法。

于 2010-10-09T20:21:27.220 回答
0

最近我需要更改 TabHost 的文本,我通过使用以下代码解决了这个问题。

请原谅我的英语,我是巴西人,我还在学习。我希望能帮助有同样问题的人。

TabHost host = (TabHost)findViewById(R.id.tabDetail);
    host.setup();

    //Tab 1
    TabHost.TabSpec spec = host.newTabSpec("tab1");
    spec.setContent(R.id.tab1);
    spec.setIndicator("Details");
    host.addTab(spec);

    //Tab 2
    spec = host.newTabSpec("tab2");
    spec.setContent(R.id.tab2);
    spec.setIndicator("Comments");
    host.addTab(spec);
于 2017-08-27T01:08:25.860 回答