如何调用添加到TabActivity的各个活动的方法?

时间:2011-08-19 13:27:53

标签: android tabactivity

我创建了一个TabActivity,它有两个标签,每个标签显示不同的活动。当用户更改选项卡时,我无法调用在这两个活动中定义的onConfigurationChanged方法。这是代码:

public class MyTabActivity extends TabActivity  implements OnTabChangeListener {

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_page);

    Resources res = getResources(); 
    TabHost tabHost = getTabHost(); 
    TabHost.TabSpec spec = null;
    Intent intent = null;

    tabHost.setOnTabChangedListener(this);


// ACTIVITY 1
    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, Activity1.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("act1").setIndicator("ACT1",
                      res.getDrawable(R.drawable.tab_home))
                  .setContent(intent);
    tabHost.addTab(spec);

// ACTIVITY 2
    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, Activity2.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("act2").setIndicator("ACT2",
                      res.getDrawable(R.drawable.tab_home))
                  .setContent(intent);
    tabHost.addTab(spec);
}


    @Override
    public void onTabChanged(String arg0) {
        Log.d("DGTabActivity", "tab changed");

        if (tabHost.getCurrentTab() == 0) {
            // How to call method on Act1??
                       callOnConfigurationChanged("com.tab.Activity1");   // doesn't work
        }
        else if (tabHost.getCurrentTab() == 1) {
            // How to call method on Act2??
        }
    }

我还尝试使用以下代码在onTabChanged方法中调用onConfigurationChanged方法,但它抛出异常:

private void callOnConfigurationChanged (String className) {
    try{
      //onConfigurationChanged
      //Class amnClass = Class.forName("android.app.ActivityManagerNative");    

      Class amnClass = Class.forName(className); 
      Object amn = null; 
      Configuration config = null; 
      Resources res = null;


      // res = amn.getResources(); 
      Method methodGetConfiguration = amnClass.getMethod("getResources"); 
      methodGetConfiguration.setAccessible(true); 
      res = (Resources) methodGetConfiguration.invoke(amn); 

      config = res.getConfiguration();

      // amn.onConfigurationChanged(config);
      Method methodOnConfigurationChanged = amnClass.getMethod("onConfigurationChanged"); 
      methodOnConfigurationChanged.setAccessible(true); 
      methodOnConfigurationChanged.invoke(amn, config); 

    }
    catch (Exception e) {
        Log.d("Tab host Exception" , e.toString());
    }

}

感谢您的时间。

欢呼声 ANI

1 个答案:

答案 0 :(得分:0)

您可以使用意图过滤器。广播配置已更改 选项卡活动中的事件,并将监听器添加到选项卡中的活动。