我的Android应用程序中有一个Activity
,它根据方向设置不同的布局XML作为其视图。我已在清单中声明android:configChanges="orientation"
。现在被称为 - 但这个时候新的方向已经生效。指定android:configChanges =“orientation”时保存状态_before_ orientation change
我的目标是尝试挂钩生命周期并尝试保存之前的新定位生效;以便在我回到当前的方向时恢复状态。
我对它进行了如下操作,但我不确定这是否是正确的方式。我的程序涉及将状态保存在中,然后调用setContentView()
来设置新方向的布局。
public class SwitchOrientationActivity extends Activity {
private View mLandscape, mPortrait;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater li = LayoutInflater.from(this);
mLandscape = li.inflate(R.layout.landscape, null);
mPortrait = li.inflate(R.layout.portrait, null);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (Configuration.ORIENTATION_LANDSCAPE == newConfig.orientation) {
switchToLandscape();
} else {
switchToPortrait();
}
}
private void switchToPortrait() {
/*
* Use mLandscape.findViewById() to get to the views and save the values
* I'm interested in.
*/
saveLanscapeState();
setContentView(mPortrait);
}
private void switchToLandscape() {
/*
* Use mPortrait.findViewById() to get to the views and save the values
* I'm interested in.
*/
savePortraitState();
setContentView(mLandscape);
}
}
有没有更好的方法来实现这个目标?
由于方向更改导致活动被破坏并重新创建,您是否总能保存onPause,onStop或onDestroy方法? – 2012-02-14 04:12:27
@Nick Campion:如果你在Manifest文件中声明了android:configChanges =“orientation”,那么当方向改变时活动不再被销毁/创建 – 2012-02-14 04:17:05
啊,我学到了一些东西。 – 2012-02-14 04:22:16