您需要在 Activity 之外保留引用,因为每次您离开时它都会被重置或 GC'd。
public class MyApplication extends Application {
public static int myIdCache = 0;
}
public class confirmTaskForm extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
MyApplication.myIdCache++;
}
}
安卓清单:
<application
android:name="com.my.package.MyApplication"
... other things
以上不是一个好的推荐编码实践
您还可以使用保持状态SharedPreferences
public class confirmTaskForm extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = getDefaultSharedPreferences();
prefs.edit().putInteger("id", prefs.getInteger("id", 0) + 1).commit();
Log.d("TAG", "Id is: " + prefs.getInteger("id"));
}
}