解锁时屏幕自动旋转

时间:2011-10-10 22:47:34

标签: android

您好我正在尝试在我的活动中保存一些值,但是当我使用onSaveInstanceState保存它并使用onRestoreInstanceState恢复时,我遇到了问题,我保存了一个int年,它保存了第一次屏幕更改方向,微调器重新填充并将其设置为最后一个值,但不是当我再次切换回方向时。

我的方向在我的清单中设置为横向,并且我重写了两个保存和恢复方法,但它似乎不起作用,我是否需要在onPause中执行某些操作?

这是我的代码:

    int years;//global variable
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Spinner spinnerYears = (Spinner) findViewById(R.id.spinYears);//Spinner
            final ArrayAdapter <Integer> adapter = new ArrayAdapter <Integer>(this,android.R.layout.simple_spinner_item );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        for(int i=0;i<=100;i++)
        {
           adapter.add(i);
        }
        spinnerYears.setAdapter(adapter);
        years = spinnerYears.getSelectedItemPosition();

   }//onCreate

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);

  savedInstanceState.putInt("MyInt", years);


}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  Spinner spinnerYears = (Spinner) findViewById(R.id.spinYears);//Spinner
    final ArrayAdapter <Integer> adapter = new ArrayAdapter <Integer> (this,      android.R.layout.simple_spinner_item );
           adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        for(int i=0;i<=100;i++)
     {
        adapter.add(i);
     }

      spinnerYears.setAdapter(adapter);
      TextView tvYears = (TextView) findViewById(R.id.tvYears);//spinner Tv
  tvYears.setVisibility(TextView.GONE);


 int myInt = savedInstanceState.getInt("MyInt");
  spinnerYears.setSelection(myInt);//
  Toast.makeText(getBaseContext(), "Restored int"+myInt, Toast.LENGTH_LONG).show();
}

2 个答案:

答案 0 :(得分:2)

因为您没有处理更改方向的事件,所以每次更改方向时,都会重新创建程序(或Activity),这意味着始终会调用onCreate()方法;这会导致onSaveInstanceState()onRestoreInstanceState()从未被调用。

Android文档中对此进行了解释:http://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges

要解决此问题,请在AndroidManifest.xml中添加此属性:

android:configChanges="orientation"

以避免重新启动Activity,祝你好运!

答案 1 :(得分:1)

onRestoreInstanceState()中,您永远不会将值赋给变量years。您将它分配给int然后忽略它。因此,当调用onSaveInstanceState()时,years尚未设置,并保存该未设置值(0)。

如果您将getInt()行更改为底部:

years = savedInstanceState.getInt("MyInt");
spinnerYears.setSelection(years);

应该开始工作了。祝你好运!