如何在tab的活动中使用setCurrentTab方法?

Koo*_*per 1 tabs android android-tabhost android-activity

我已经有这个问题1周了.
MainActivity extends TabActivity在每个标签中都有A和B两个活动.
现在我想按活动A中的按钮将当前页面设置为活动B的选项卡
但是我不能使用setCurrentTab方法除外MainActivity.如何使此功能起作用?

public class MainActivity extends TabActivity

public TabHost tabHost; 

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

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

    tabHost.setCurrentTab(0);

}
Run Code Online (Sandbox Code Playgroud)

public class AActivity extends Activity{

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_layout);
        Button b = (button)findViewById(R.id.bt);
        b.setOnClickListener(this);
    }
    public void onClick(View v) {
        tabHost.setCurrentTab(1);
        //Can't work here
    }
}
Run Code Online (Sandbox Code Playgroud)

MainActivity extends TabActivity

setCurrentTab

Eld*_*abu 5

尝试进行以下更改:

在主要活动中:

  1. 使tabHost变量为Static.

    private static TabHost tabHost;

  2. 添加新函数以获取当前tabhost.

    public static TabHost getCurrentTabHost(){ return tabHost; }

  3. 在AActivity中,使用如下:

    MainActivity.getCurrentTabHost().setCurrentTab(1);

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