我发现很多例子在android中使用xml文件创建标签,但我需要以编程方式创建多个标签。请指导我。
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:tag="tab0"
android:text="Tab 1"
android:background="@android:drawable/btn_star_big_on"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
/>
<TextView
android:tag="tab1"
android:text="Tab 2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
/>
<TextView
android:tag="tab2"
android:text="Tab 3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
/>
</TabWidget>
如何以编程方式编写此代码而不是上述xml代码。
答案 0 :(得分:4)
检查 Tab With Swipe 示例。它实现了没有xml文件的选项卡。
但是每个片段都有XML布局。您可以根据自己的要求删除它。
答案 1 :(得分:0)
在TabActivity中:
private void addTab(String labelId, int drawableId, Class<?> c)
{
Intent intent=new Intent(this, c);
TabHost.TabSpec spec=Your_TabHost.newTabSpec("tab"+labelId);
View tabIndicator=LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title=(TextView)tabIndicator.findViewById(R.id.title);
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
title.setText(labelId);
ImageView icon=(ImageView)tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
Your_TabHost.addTab(spec);
}
通过这种方式添加标签(仍在TabActivity中):
addTab("Your tab title", R.drawable.your_tab_icon, SomeActivity.class);
但我仍强烈建议你在低于4.0的android中使用ActionBarSherlock,因为Tab已被弃用...