如何存储值并在方向更改时检索它?

时间:2011-06-22 09:03:31

标签: android orientation

我已经检查了很多帖子,并且根据我已经完成了方向更改的编码。方向更改时,问题是我无法在TextViews中检索输入的值。任何人都可以告诉我哪里出错了吗?

编码:

在我添加的相应活动的清单文件中:

android:configChanges="orientation|keyboardHidden"

在活动中,我添加了以下方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_screen);
    //Initialized the widgets
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    //have written separate layout files for portrait and landscape
    setContentView(R.layout.home_screen); 
    //Initialized the widgets again
    retrieveSavedState();  //sets the TextViews again
}

@Override
protected void onPause() {
    super.onPause();
    saveState(); //save the TextView values
}

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    saveState();
}

@Override
protected void onResume() {
    super.onResume();
    retrieveSavedState();
}

1 个答案:

答案 0 :(得分:1)

@Override
public Object onRetainNonConfigurationInstance() 
{
    final MyDataObject data = collectMyLoadedData();
    return data;
}

上述方法可用于保存任何对象以保存数据......

@Override
public void onCreate(Bundle savedInstanceState)
 {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
    if (data == null) {
        data = loadMyData();
    }
    ...
}

你可以在onCreate()中检索当我们在方向改变时调用的对象..从该对象读取数据后,你可以在任何你想要的地方使用它。

http://developer.android.com/guide/topics/resources/runtime-changes.html

http://developer.android.com/guide/topics/resources/runtime-changes.html

其他机制也存在,但这是我所知道的最佳方式..您还可以使用共享首选项来存储和检索数据......

http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html