android - 如何在选项卡的 Activity 中使用 setCurrentTab 方法?

标签 android android-activity tabs android-tabhost

我已经遇到这个问题 1 周了。
我在每个选项卡中有一个 MainActivity extends TabActivity 和 A、B 两个 Activity 。
现在我想在 Activity A 中按下一个按钮,将当前页面设置为 Activity B 的选项卡
但是除了在 MainActivity 中,我不能使用 setCurrentTab 方法。 我怎样才能使这个功能发挥作用?

公共(public)类 MainActivity 扩展 TabActivity

public TabHost tabHost;

@覆盖
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    资源 res = getResources();
    tabHost = getTabHost();
    TabHost.TabSpec 规范;
     Intent ;
    intent = new Intent().setClass(this, StartActivity.class);
    spec = tabHost.newTabSpec("tab1").setIndicator("A",res.getDrawable(R.drawable.start))
                  .setContent( Intent );
    tabHost.addTab(规范);

    intent = new Intent().setClass(this, WeatherActivity.class);
    spec = tabHost.newTabSpec("tab2").setIndicator("B",res.getDrawable(R.drawable.weather))
                  .setContent( Intent );
    tabHost.addTab(规范);

    tabHost.setCurrentTab(0);

}

公共(public)类 AActivity 扩展 Activity{

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_layout);
        按钮 b = (按钮)findViewById(R.id.bt);
        b.setOnClickListener(this);
    }
    public void onClick(View v) {
        tabHost.setCurrentTab(1);
       //这里不能工作
    }
}

最佳答案

尝试进行以下更改:

在主要 Activity 中:

  1. 将 tabHost 变量设为静态。

    private static TabHost tabHost;

  2. 添加一个新函数来获取当前的 tabhost。

    public static TabHost getCurrentTabHost(){ 返回标签主机; }

  3. 在 AActivity 中,像这样使用:

    MainActivity.getCurrentTabHost().setCurrentTab(1);

如果需要,您可以进行空检查。

关于android - 如何在选项卡的 Activity 中使用 setCurrentTab 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13448371/

相关文章:

java - CTab文件夹渲染器

javascript - 使用 jQuery 选项卡交换图像

android-fragments - android - 对多个 Activity 使用相同的片段

java - 如何在用户按下 imageButton 之间添加延迟?

java - 如何使用 Android 配置 Proguard,使其不会删除仅在 XML 布局中引用的事件处理程序方法?

c# - 重启设备后出现图片

android - 当应用程序从后台进入前台时启动特定的 Activity

android - 按下 ListView 项时以动画开始 Activity

java - 如何将按钮对齐到选项卡内的中心?

android - getDrawable() 内存不足错误