1

我的ActivityAndroid 应用程序中有一个根据方向将不同的布局 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);

    }
}

有没有更优雅的方法来实现这一点?

4

1 回答 1

0

android:configChanges="orientation"导致您的活动不会在方向更改时重新启动,因此会为此跳过常规生命周期。我建议,你把它拿出来,然后实现onRetainNonConfigurationInstance () 并在 onCreate 或 onRestoreInstanceState 中恢复你的状态。有关更多信息,请参阅本文

于 2012-02-14T04:18:47.890 回答