详细地说,我在界面SharedPreferences
的帮助下计算我的应用程序打开的次数,并在屏幕上显示计数,但是当我更改orientation
时,计数仍会增加。
我不想以纵向方式粘贴布局,我希望我的应用可以使用两种方向,onCreate()
的代码如下所示:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate!");
mPrefs = getPreferences(MODE_PRIVATE);
int count = mPrefs.getInt(COUNT, 0);
count = count + 1;
Editor editor = mPrefs.edit();
editor.putInt(COUNT, count);
editor.commit();
mTextView = new TextView(this);
mTextView.setTextSize(40);
mTextView.setText("Count: " + count);
Log.d(TAG, "Count is " + count);
setContentView(mTextView);
// setContentView(R.layout.activity_main);
mTextView.setOnClickListener(this);
}
答案 0 :(得分:0)
只要设备方向发生变化,就会调用OnCreate。请尝试将相关代码放入OnStart中。
答案 1 :(得分:0)
您只能在未通过savedInstanceState
保存时增加计数,因为在更改方向时会调用onSaveInstaceState
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY)){
count = savedInstanceState.getInt(KEY);
}
} else {
count = mPrefs.getInt(COUNT, 0);
count += 1;
Editor editor = mPrefs.edit();
editor.putInt(COUNT, count);
editor.commit();
}
}
@Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY, count);
}