如何在Android中不使用XML创建多个选项卡

3
我在 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代码。

使用ActionBar选项卡!请参见http://developer.android.com/guide/topics/ui/actionbar.html#Tabs - Tomasz Gawel
http://learnandroideasily.blogspot.in/2013/07/android-tabwidget-example.html - Chintan Rathod
如果我使用import android.app.ActionBar,它会显示错误“无法解析”。 - sivanesan1
我使用的是Android 2.3.3版本。其中ActionBar无法正常工作。 - sivanesan1
@Chintan:请更新一些示例代码,我的网络过滤器拦截了使用的博客网址。 - sivanesan1
2个回答

4

请查看带有滑动功能的选项卡示例Tab With Swipe。它实现了无需xml文件的选项卡。

但是每个片段都有XML布局,您可以根据需要删除它。


我需要在没有布局XML文件的情况下创建。我需要编写程序,而不使用任何XML文件。 - sivanesan1
@sivanesan1,很高兴能帮忙.. 如果您能点赞就更好了.. :) - Chintan Rathod

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);

但我仍然强烈建议您在 Android 4.0 以下使用 ActionBarSherlock,因为 Tab 已被弃用...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接