更改Android选项卡上的文本

更改Android选项卡上的文本,android,android-tabhost,Android,Android Tabhost,我有一个Android应用程序,在TabHost中有3个选项卡(文本标签,没有图像)。我将选项卡设置为: intent = new Intent().setClass(this, AnnouncementsActivity.class); spec = tabHost.newTabSpec("news").setIndicator("News").setContent(intent); tabHost.addTab(spec); 我启动了一个后台线程从我的服务器获取公告,我想更新选项卡上的文本

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

intent = new Intent().setClass(this, AnnouncementsActivity.class);
spec = tabHost.newTabSpec("news").setIndicator("News").setContent(intent);
tabHost.addTab(spec);
我启动了一个后台线程从我的服务器获取公告,我想更新选项卡上的文本标签,告诉用户有多少新公告。例如,我想将选项卡上的文本更改为“新闻(3)”。如何访问和更改选项卡上的文本标签


欢迎提出任何建议

查看演示的代码,查看代码末尾的获取textView的方法

你可以这样做

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

如果系统生成了
android.R.id.title
,只需根据您的需要更改ChildIndexText,就可以获得更高版本的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");
}
FragmentTabHost tabHost=(FragmentTabHost)view.findviewbyd(android.R.id.tabHost);
AppCompatTextView tv=null;
RelativeLayout parentLayout=(RelativeLayout)tabHost.getTabWidget().getChildAt(0);
对于(int i=0;i
我所做的只是通过调试器运行它并找出层次结构。我无法让android.R.id.title正常工作,因为文本视图现在被另一个id引用。无论如何,它现在也是一个AppCompatTextView,而不是一个普通的旧文本视图

同样,这是非最优的,但是对于更新版本的android来说,它得到了期望的结果


希望这有帮助

最近我需要更改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);

谢谢你的回复。我访问TabHost没有问题,我的问题是在TabHost中找不到任何允许我更改选项卡上文本的内容。一旦我有了TabHost参考,我如何更改文本?好的,谢谢链接。你是对的,这真的很有技巧,我不知道为什么没有更简单的方法,但它对我很有效,所以现在就可以了。再次感谢!对我来说,它为textView提供了空指针异常。你能给我解释一下吗?@ParthibanM请看我下面的帖子,作为你空指针异常的可能解决方案。