【问题标题】:Example of using Android tabs with Views instead of Activities?使用带有视图而不是活动的 Android 选项卡的示例?
【发布时间】:2011-02-27 14:08:32
【问题描述】:

Android 开发者 TabWidget 教程如下:

“您可以通过以下两种方式之一实现您的选项卡内容:使用选项卡在同一个 Activity 中交换视图,或使用选项卡在完全独立的活动之间切换。”

本教程继续演示如何使用带有单独活动的选项卡。我一直无法找到在同一活动中使用具有不同视图的选项卡的示例。我宁愿不重新发明这个特定的轮子,所以我希望这里有人知道这是如何完成的,并且可以提示我。谢谢!

【问题讨论】:

  • 这个问题是它扩展了已弃用的 TabActivity。

标签: java android android-widget


【解决方案1】:

我认为在您希望使用的视图中传递的每个选项卡的 .setContent 方法中:

TabHost.TabSpec spec1 = tabs.newTabSpec("tag1");
spec1.setContent(R.id.AnalogClock01);
spec1.setIndicator("Analog Clock");

这是我不久前找到的一个例子:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

  <TabHost android:id="@+id/TabHost01" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TabWidget android:id="@android:id/tabs" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <FrameLayout android:id="@android:id/tabcontent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="65px">
      <AnalogClock android:id="@+id/AnalogClock01" android:layout_width="wrap_content" android:layout_height="wrap_content"></AnalogClock>
      <DigitalClock android:text="DigitalClock01" android:id="@+id/DigitalClock01" android:layout_width="wrap_content" android:layout_height="wrap_content"></DigitalClock>
    </FrameLayout>
  </TabHost>
</LinearLayout>

这个例子的Java代码如下:

import android.app.Activity;
import android.os.Bundle;
import android.widget.TabHost;

public class tabexample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TabHost tabs = (TabHost)findViewById(R.id.TabHost01);

        tabs.setup();

        TabHost.TabSpec spec1 = tabs.newTabSpec("tag1");

        spec1.setContent(R.id.AnalogClock01);
        spec1.setIndicator("Analog Clock");

        tabs.addTab(spec1);

        TabHost.TabSpec spec2 = tabs.newTabSpec("tag2");
        spec2.setContent(R.id.DigitalClock01);
        spec2.setIndicator("Digital Clock");

        tabs.addTab(spec2);
    }
}

【讨论】:

  • 如果我必须在每个视图上执行一些“任务”怎么办?例如,如果我必须在 View1 上解析一些 XML 并在 View2 上查询 SQLITE 数据库后显示数据?在这种情况下,为每个选项卡编写单独的活动是唯一的解决方案吗?
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多