gpt4 book ai didi

android - 如何获取 TabHost 中 Tab 的内容?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:39 25 4
gpt4 key购买 nike

我有一个 Activity 定义为:

<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() 在那一刻只引用 Activity 选项卡,所以如果我想向未选择的选项卡的 TextView 添加一些文本,我必须事先使用 .setCurrentTab(i) 选择它,什么意味着我要更改 Activity 标签...

我认为这一定比我想象的要容易得多...对此有任何帮助吗?

谢谢!

--------编辑--------

那时我意识到无法访问非 Activity 选项卡的内容。至少不是那样。假设您无法访问非 Activity 选项卡的 View ,因为它没有关联 View ,至少不是公共(public) View 。

我尝试声明一个 Map,其中第一个字符串是选项卡的名称,第二个是与其内容关联的 TextView,并在创建选项卡时分配它们。结果是我只能引用 Activity 选项卡的 TextView,其他的则抛出 NullPointer 异常。

所以我以不同的方式关注问题。现在,如果我必须将一些文本添加到非 Activity 选项卡中,我将该文本添加到哈希,声明一个 OnTabChangeListener,每次更改选项卡时,我都会将待处理的内容转储到其中。

这不是最出色的解决方案,但它是我唯一的解决方案...所以如果有人对此有更好的解决方案,我将不胜感激。

最佳答案

@nKn,感谢 getTabContentView()。在我的例子中,它返回的不是一个选项卡,而是一个包含所有选项卡的 FrameLayout,以及以下工作:

View tab = tabHost.getTabContentView().getChildAt(2);
ImageView image = (ImageView) tab.findViewById(R.id.image);

关于android - 如何获取 TabHost 中 Tab 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20030408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com