[英]Saving state _before_ orientation change when android:configChanges=“orientation” is specified
我的Android應用程序中有一個“ Activity
,它根據方向將不同的布局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);
}
}
有沒有更優雅的方法來實現這一目標?
android:configChanges="orientation"
導致您的活動不會在方向更改時重新啟動,因此跳過了常規生命周期。 我建議您將其刪除,然后實現onRetainNonConfigurationInstance ()並在onCreate或onRestoreInstanceState中恢復您的狀態。 有關更多信息,請參見本文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.