你好,TabWidget每个选项卡都引用新的xml
-
25-09-2019 - |
题
我正在使用 Google 的 example 你好,TabWidget 但将其更改为如下所示:
主要.xml:
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="@+layout/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<TextView
android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is another tab" />
<TextView
android:id="@+id/textview3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is a third tab" />
</FrameLayout>
</LinearLayout>
</TabHost>
java 文件:
public class HelloTabWidget extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(R.layout.text));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(R.id.textview2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(R.id.textview3));
mTabHost.setCurrentTab(0);
}
}
这是 res/layout 中的 text.xml:
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="This is Tab 1" />
</LinearLayout>
我基本上想做的是让每个选项卡引用其自己的 xml 文件,而不是 main.xml 中的所有文件,但第一个选项卡中的文本不会显示。
解决方案
您想有每个选项卡是指自己的Activity
?如果是这样,则可以设置一个意图作为用于每个选项卡内容:
intent = new Intent().setClass(this, Test.class);
spec = tabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(intent);
tabHost.addTab(spec);
当然,你则必须有一个名为Test(或任何其他)类集合test.xml
作为布局。
public class Test extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
}
本教程将帮助你进一步,如果是这样的键入的场景,你想建立的。
其他提示
使用内置选项卡主机的选项卡有三个选项。
- 使用一个布局文件对单个活动进行多个视图
- 多项活动
- TabContentFactory 中内置的自定义视图
听起来你想要#3。你需要做的是这样的:
setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag)
{
View view = LayoutInflater.from(HelloTabWidget.this).inflate(R.layout.text);
// Setup the view here
return view;
}});
View view = LayoutInflater.from(HelloTabWidget.this).inflate(R.layout.text);
这是不完全正确如LayoutInflater.inflate有两个参数。
不隶属于 StackOverflow