我在处理活动中的onCreate()时遇到了一个主要问题。就像thread说的,我只能执行main活动的onCreate()方法中的一部分代码一次。因此,我按照该线程中的步骤执行了以下操作:
/*I've updated the code to SharePreferences version*/
public class MyApp extends Activity {
private static RMEFaceAppActivity instance;
private boolean wascalled = false;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//initiate some buttons here
sharedPreferences = this.getSharedPreferences("test",0);
editor = sharedPreferences.edit();
if(sharedPreferences.getString("wascalled", "false").equalsIgnoreCase("false"))
{
//work can only be done once
editor.putString("wascalled", "true");
editor.commit();
}
//set buttons to listener methods
}
void onClick(View arg0)
{
if(arg0.getId() == R.id.button1)
{
Intent intent = new Intent(this, MyChildApp.class);
startActivity(intent);
}
}
}在MyChildApp类中,当工作完成时,我调用了finish()。但是,字段wascalled始终为false。我认为当第二次执行从MyChildApp返回的onCreate()时,wascalled应该已经设置为true。每次从MyChildApp返回时,onCreate()方法中的if语句中的代码都会执行。
有人对此有什么建议吗?在此之前非常感谢。
发布于 2012-08-16 23:47:58
wascalled将始终为false,因为它是活动实例的一部分。它是在你的活动中声明的:
private boolean wascalled = false;当重新创建活动时,所有实例变量都初始化为它们的默认值,这就是为什么您得到always false的原因。
如果您注意到该thread中的代码,您会注意到该wascalled是另一个类的一部分,而不是Activity的类。
if (!YourApplicationInstance.wasCalled) {
}在这个具体的示例中,YourApplicationInstance是一个单独的类,它保持wascalled的状态为变量。
https://stackoverflow.com/questions/11990827
复制相似问题