![](/img/trans.png)
[英]onCreate not getting called for first activity when calling startActivity consecutively for two different activities
[英]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.