这就是我想要实现的目标:
在 TabWidget 中使用 TextView(即调用TabHost.TabSpec.setIndicator(View)
代替TabHost.TabSpec.setIndicator(String)
).
我想在 XML 中配置 TextView,而不是以编程方式构建它。
所以最初,在我的布局 XML 中,我有:
<TabHost
android:id="@+id/mainTabHost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="30px"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="30px">
</FrameLayout>
</TabHost>
现在我想将 TextView 配置放入某处。它实际上并不“属于”嵌套在布局层次结构中的任何位置。但是,由于布局 XML 当然必须是有效的 XML,因此它不能有多个根元素。所以我被迫将 TextView 嵌套在某个地方。因此,我只是将其放在根目录下一层(TabHost):
<TabHost
android:id="@+id/mainTabHost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="30px"/>
<TextView
android:id="@+id/tvTabIndicatorPreferences"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="@string/tab_name_preferences"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="30px">
</FrameLayout>
</TabHost>
在我的代码中我这样做:
final TabHost mainTabHost = (TabHost) this.findViewById(R.id.mainTabHost);
mainTabHost.setup();
final TextView tvTabIndicatorPreferences = (TextView) this.findViewById(R.id.tvTabIndicatorPreferences);
final TabHost.TabSpec tabSpecPreferences = mainTabHost.newTabSpec("tabPreferences");
tabSpecPreferences.setIndicator(tvTabIndicatorPreferences);
tabSpecPreferences.setContent(R.id.scrlTblPreferences);
mainTabHost.addTab(tabSpecPreferences);
但这里有一个问题。当我尝试运行该应用程序时,我收到一个异常,上面写着
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
这绝对是合乎逻辑和合理的。 TextView 已经是 TabHost 的子级。我不能只是将其设置为另一个元素的子元素。 (注意:将 TextView 嵌套在 TabWidget 下会产生相同的结果。)
所以我不得不打电话mainTabHost.removeView(tvTabIndicatorPreferences)
在致电之前setIndicator
.
它确实有效,但这种做法对我来说感觉非常错误。首先,我必须将 TextView 放入 XML 中不属于它的位置,然后在代码中将其从不属于它的位置中删除,然后再使用它。
在这种情况下,实现这一目标的正确方法是什么?