我正在尝试创建一个基本应用程序,该应用程序只计算用户将方向从纵向更改为横向的次数,并在屏幕上显示计数。我有:
public class MainActivity extends Activity {
int count = 0;
private static boolean inLandscape = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.count);
tv.setText(getResources().getString(R.string.count) + ' ' + count);
if (!inLandscape && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
inLandscape = true;
count++;
Log.e("Debug","In Landscape " + count);
}
else if (inLandscape && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
inLandscape = false;
}
问题是,在我的调试语句中,count始终为1,并且文本永远不会在屏幕上更改。做一些研究,我认为这是因为每次方向改变时,活动都会被删除并重新创建。如何在整个方向变化中保持变量值?
我尝试将savedInstanceState与
一起使用if (savedInstanceState.containsKey("count"))
count = savedInstanceState.getInt("count");
savedInstanceState.putInt("count", count);
但是这会在containsKey
行给出NullPointerException。
答案 0 :(得分:1)
覆盖onSaveInstanceState
以存储您的方向更改计数器。
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("count", count)
}
并覆盖onRestoreInstanceState
以便在更改后将其读回。
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
count = savedInstanceState.getInt("count");
}
显然,您仍然可以将代码保存在'onCreate'中的相同位置,以便每次调用onCreate时根据方向有条件地添加到计数器。
答案 1 :(得分:1)
它给你一个NullPointerException,因为saveInstanceState为null。您还需要将savedInstanceState.putInt("count", count)
放在onRestoreInstanceState
方法中。所以你的代码看起来像......
int mCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.count);
mCount = 0;
tv.setText(getResources().getString(R.string.count) + ' ' + mCount);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mCount++;
tv.setText(getResources().getString(R.string.count) + ' ' + count);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
mCount = savedInstanceState.getInt("count");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("count", mCount);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
有关详细信息,请参阅http://developer.android.com/training/basics/activity-lifecycle/recreating.html和http://developer.android.com/guide/topics/resources/runtime-changes.html。