簡體   English   中英

Android Eclipse是兩個不同選項卡中的兩個活動,一直在調用onCreate()!

[英]Android Eclipse, two activities in two different tabs, keeps calling onCreate()!

我有2個活動,比方說Activity1和Activity2。 我已經將這2個添加到TabHost下的2個單獨的選項卡中。

每次我按所需的選項卡查看內容時,每個活動的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中使用“活動”的代碼。 理想情況下,一旦創建了選項卡,活動將調用onResume而不是onCreate,因為當您從一個選項卡移動到另一個選項卡時,這些活動不會被破壞。

替換此TabSpec firstTabSpec = tabHost.newTabSpec(“ tid1”);
TabSpec secondTabSpec = tabHost.newTabSpec(“ tid1”); 與:

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

為了保留內存,一次要加載盡可能少的活動。 當未顯示選項卡時,由於活動不可見,因此該活動被破壞。

您要么不應該為每個選項卡創建一個活動,而是要在同一活動中為每個選項卡創建不同的視圖,要么應該保存該活動的狀態以供再次加載時使用。

這里有一個有關如何在不進行活動的情況下制作Tabhost的小示例: http ://dewful.com/?p=15

對我來說,問題與上面的PravinCG一樣。 確保所有TabSpec中的標簽都是唯一的,即可輕松解決該問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM