【发布时间】:2014-12-17 16:51:51
【问题描述】:
我想知道以编程方式将选项卡添加到选项卡主机的最简单方法(例如,通过按下按钮)。换句话说,无需在 XML 文件中对其结构进行硬编码。
【问题讨论】:
我想知道以编程方式将选项卡添加到选项卡主机的最简单方法(例如,通过按下按钮)。换句话说,无需在 XML 文件中对其结构进行硬编码。
【问题讨论】:
以编程方式创建选项卡并为其填充内容的一种方法是:
TabSpec.setContent 方法的参数单独的 Layout.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:text="Kablam"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/kablamTextView" />
</LinearLayout>
TabContent Factory 类(定义为Activity 中的内部类 => this 是活动实例)
private class MyTabContentFactory implements TabContentFactory {
public View CreateTabContent(string tag) {
View view = this.getLayoutInflater()
.inflate(R.layout.Layout, (ViewGroup)this.FindViewById(R.id.tabHost1), false);
((TextView)view.findViewById(R.id.kablamTextView))
.setText("Some sentence which can be generated dynamically");
return view;
}
}
最后以Hemendra Sharma 的回答为基础,使用标签工厂来定义内容
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
TabSpec tab1 = tabHost.newTabSpec("Tab_Name");
tab1.setIndicator("Tab 1");
tab1.setContent(new MyTabContentFactory());
tabHost.addTab(tab1);
【讨论】:
这是一种以编程方式在 TabHost 上添加选项卡的简单方法。
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
TabSpec tab1 = tabHost.newTabSpec("Tab_Name");
View view = getLayoutInflater().inflate(R.layout.tab_indicator,
myLayout, false);
tab1.setIndicator(view);
Intent i = new Intent(getApplicationContext(), MyActivity.class);
tab1.setContent(i);
tabHost.addTab(tab1);
祝你好运。 :)
【讨论】:
在按钮点击事件上,试试这个
myTabHost =(TabHost) findViewById(R.id.tabhostId);
mytabhost.setup();
TabSpec spec = mytabhost.newTabSpec("tab_creation");
spec.setIndicator("TAB_NAME",getResources().getDrawable(android.R.drawable.ic_menu_add));// text and image of tab
spec.setContent(R.id.layout_of_tab); // layout of tab
mytabhost.addTab(spec);
【讨论】: