在TabHost中有两个子activity,这两个子activity在两个tab中。在其中的一个activity实现了一个公共函数,我想从父类TabHost中调用这个函数,来触发tab中的一些action。
能否从TabHost中引用activity本身来调用一个公共函数?
tabhost设置:
res = getResources();
tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, home.class);
spec = tabHost.newTabSpec("home").setIndicator("Groups", res.getDrawable(R.drawable.groups)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, messages.class);
spec = tabHost.newTabSpec("messages").setIndicator("Messages", res.getDrawable(R.drawable.messages)).setContent(intent);
tabHost.addTab(spec);
是之前遇见过这个问题是这样解决的:
1.在manifest文件中设置intent filter
2.给子activity添加嵌套的'listener'
3.在子activity的onResume()/onPause()到register/unregister监听器
4.在TabActivity创建intent,然后广播。
AndroidManifest.xml
<activity
android:name=".MyActivity"
android:label="@string/app_name"
<intent-filter>
<action android:name="com.mycompany.myApp.DO_SOMETHING" />
</intent-filter>
</activity>
MyActivity.java
public class MyActivity extends Activity {
private MyListener listener = null;
private Boolean MyListenerIsRegistered = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreated(savedInstanceState);
listener = new MyListener();
}
@Override
protected void onResume() {
super.onResume();
if (!MyListenerIsRegistered) {
registerReceiver(listener, new IntentFilter("com.mycompany.myApp.DO_SOMETHING"));
MyListenerIsRegisterd = true;
}
}
@Override
protected void onPause() {
super.onPause();
if (MyListenerIsRegistered) {
unregisterReceiver(listener);
MyListenerIsRegistered = false;
}
}
// Nested 'listener'
protected class MyListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// No need to check for the action unless the listener will
// will handle more than one - let's do it anyway
if (intent.getAction().equals("com.mycompany.myApp.DO_SOMETHING")) {
// Do something
}
}
}
}
main TabActivity
private void MakeChildDoSomething() {
Intent i = new Intent();
i.setAction("com.mycompany.myApp.DO_SOMETHING");
sendBroadcast(i);
}
希望能帮你解决问题:
Activity currentActivity = getLocalActivityManager().getActivity(_TabHost.getCurrentTabTag());
if(currentActivity != null && currentActivity instanceof iMyActivity)
{
// 传递给子类
((iMyActivity)currentActivity).onLaunchDelegate();
}