在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);
}