Android Eclipse,两个活动在两个不同的选项卡,不断调用onCreate()



我有两个活动,我们设为Activity1和Activity2。我已经将这两个添加到TabHost下的两个单独的选项卡中。

每次我按下所需的选项卡来查看内容时,每个活动的onCreate()被调用,因此重新启动活动!为什么呢?我怎样才能防止这种情况发生??

谢谢。

TabHostActivity类的代码:

package zt.ztactive;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
 public class TabHostActivity extends TabActivity { 
     TabHost tabHost;
     /** Called when the activity is first created. */
     @Override 
     public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         setContentView(R.layout.tabwindow);  
         /** TabHost will have Tabs */ 
         tabHost = (TabHost)findViewById(android.R.id.tabhost); 
         /** TabSpec used to create a new tab.  
          * By using TabSpec only we can able to setContent to the tab.  
          * By using TabSpec setIndicator() we can set name to tab. */
         /** tid1 is firstTabSpec Id. Its used to access outside. */ 
         TabSpec firstTabSpec = tabHost.newTabSpec("tid1");  
         TabSpec secondTabSpec = tabHost.newTabSpec("tid1"); 
         /** TabSpec setIndicator() is used to set name for the tab. */ 
         /** TabSpec setContent() is used to set content for a particular tab. */ 
         firstTabSpec.setIndicator("First Tab Name").setContent(new Intent(this,Activity1.class));  
         secondTabSpec.setIndicator("Second Tab Name").setContent(new Intent(this,Activity2.class)); 
         /** Add tabSpec to the TabHost to display. */ 
         tabHost.addTab(firstTabSpec);  
         tabHost.addTab(secondTabSpec);  
     }
 }

你能展示一些代码来说明你是如何在你的tabhost中使用Activities的吗?理想情况下,一旦标签被创建,活动将调用onResume而不是onCreate,因为当你从一个标签移动到另一个标签时,活动不会被破坏。

为了节省内存,在一个点上加载尽可能少的活动。当选项卡不显示时,活动是不可见的,活动被销毁。

或者你不应该为每个选项卡创建一个活动,而是在同一个活动中为每个选项卡创建不同的视图,或者你应该保存活动的状态,以便再次加载。

这里有一个关于如何制作没有活动的标签的小示例:http://dewful.com/?p=15

替换TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid1");:

TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid2");

我遇到的问题与PravinCG上面描述的问题相同。确保所有tabspec中的标签都是唯一的,很容易解决这个问题!

最新更新