我已经遇到这个问题 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 中:
将 tabHost 变量设为静态。
private static TabHost tabHost
;添加一个新函数来获取当前的 tabhost。
public static TabHost getCurrentTabHost(){ 返回标签主机; }
在 AActivity 中,像这样使用:
MainActivity.getCurrentTabHost().setCurrentTab(1);
如果需要,您可以进行空检查。
关于android - 如何在选项卡的 Activity 中使用 setCurrentTab 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13448371/