题
我在TABHOST中有一个带有3个选项卡的Android应用(文本标签,没有图像)。我像这样设置了标签:
intent = new Intent().setClass(this, AnnouncementsActivity.class);
spec = tabHost.newTabSpec("news").setIndicator("News").setContent(intent);
tabHost.addTab(spec);
我启动了一个背景线程以从服务器获取公告,我想在选项卡上更新文本标签,以告诉用户有多少个新公告。例如,我想将标签上的文本更改为“新闻(3)”。如何访问和更改标签上的文本标签?
欢迎任何建议!
解决方案
查看演示的代码 这里, ,请参阅代码末尾,有骇人听闻的方法来获取文本视图。
其他提示
你可以这样做
TabHost tabHost = getTabHost();
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);
tv.setText("New Tab Text");
在哪里 android.R.id.title
是生成系统的,只需更改 ChildIndex 和 文本 根据您的需要
对于以后版本的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");
}
我所做的就是通过调试器运行并找出层次结构。由于文本视图现在由其他ID引用,因此我无法让Android.r.id.title起作用。无论如何,它现在也是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);
不隶属于 StackOverflow