我的Activity
Android 应用程序中有一个根据方向将不同的布局 XML 设置为其视图。我已经android:configChanges="orientation"
在清单中声明了。现在onConfigurationChanged()
调用 - 但此时新的方向已经生效。
我的目标是尝试融入生命周期并尝试在新方向生效之前保存一些更改;这样当我回到当前方向时,我就可以恢复状态。
我按如下方式对其进行了破解,但我不确定这是否是正确的方法。我的过程涉及保存状态,onConfigurationChanged()
然后调用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);
}
}
有没有更优雅的方法来实现这一点?