【发布时间】:2013-11-17 12:00:49
【问题描述】:
我有一个由以下人员定义的活动:
<LinearLayout
android:id="@+id/TabContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="99"
android:orientation="vertical">
<TabHost
android:id="@+android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/TabLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@+android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="@+android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"></FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
基本上它是一个以 TextViews 作为内容的 TabHost。我正在使用 createTabContent() 动态构建这些 TextView 的选项卡和内容。这很好用。但在某些情况下(某些事件由带有 TCP 套接字的 AsyncTask 处理),我需要更改其中一些 TextView 的内容。
我确信我的问题是由于我对 Android SDK 缺乏经验,但我无法找到一种方法来迭代 TabHost 并获取每个 TextView 的内容。
我实现的“最接近”的方法是:
TabHost th = (TabHost) findViewById(android.R.id.tabhost);
TabWidget tw = th.getTabWidget();
for (int i = 0; i < tw.getChildCount(); i++) {
LinearLayout lLayout = (LinearLayout) tw.getChildAt(i);
TextView tv = ((TextView) lLayout.getChildAt(i));
tv.append(linea);
}
但这所做的是将“linea”附加到选项卡的名称(到指示器)。我想将它添加到该选项卡的 content 中,但我找不到检索与其关联的 TextView 的方法。
任何想法都将不胜感激!
--------- 编辑 ---------
虽然我在下面的评论中发布了我已经有了解决方案,但我发现它无效。代码现在看起来像这样:
for (int i = 0; i < tw.getChildCount(); i++) {
LinearLayout LLayout = (LinearLayout) tw.getChildAt(i);
TextView currenttab = (TextView) LLayout.getChildAt(0);
if (tab.equals(currenttab.getText())) {
th.setCurrentTab(i);
TextView tabContent = (TextView) th.getTabContentView().getChildAt(0);
tabContent.append(linea);
return true;
}
}
问题是 getTabContentView() 只引用了当前的活动选项卡,所以如果我想在未选择的选项卡的 TextView 中添加一些文本,我必须先用 .setCurrentTab(i) 选择它,什么意味着我将更改活动选项卡...
我认为这必须比我想象的要容易得多...有什么帮助吗?
谢谢!
--------- 编辑 ---------
那时我已经意识到访问非活动标签的内容是不可能的。至少不是那样。假设您无法访问非活动选项卡的视图,因为它没有关联的视图,至少没有公共视图。
我尝试声明一个 Map,其中第一个 String 是选项卡的名称,第二个是与其内容关联的 TextView,并在选项卡创建时分配它们。结果是我只能引用活动选项卡的TextView,其他的都抛出了NullPointer异常。
所以我以不同的方式关注问题。现在,如果我必须将一些文本添加到非活动选项卡中,我将该文本添加到哈希中,我声明了一个 OnTabChangeListener,并且每次更改选项卡时,我都会将待处理的内容转储到其中。
这不是最出色的解决方案,但它是我唯一的工作......所以如果有人对此有更好的解决方案,我将不胜感激。
【问题讨论】:
标签: android android-layout android-activity android-tabhost android-view