我这个问题已经持续了一周
我在每个标签中都有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);
}
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);
}
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
}
}
答案 0 :(得分:5)
尝试进行以下更改:
在主要活动中:
将tabHost变量设为静态。
private static TabHost tabHost
;
添加新函数以获取当前tabhost。
public static TabHost getCurrentTabHost(){
return tabHost;
}
在AActivity中,使用如下:
MainActivity.getCurrentTabHost().setCurrentTab(1);
如果需要,您可以进行空检查。