onConfigurationChanged-它仍然显示第一个布局

时间:2010-10-23 09:08:11

标签: android android-manifest

我有一个处理配置更改的活动。但现在我必须改变 layout.I尝试onConfigurationChanged回调只是为了再次设置布局,并希望得到正确的布局(土地),但它仍然显示 纵向视图的第一个布局(有两个布局(相同名称)放在res / 布局和res / layout-land:)

如果我删除android:configChanges =“orientation”,它应该是,但是需要处理onConfigurationChanged。我该怎么办??

2 个答案:

答案 0 :(得分:16)

如果main.xml中的纵向布局/res/layoutmain.xml中的横向布局/res/layout-land,您的onConfigurationChanged()如下所示:

    public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);                
            setContentView(R.layout.main);
    ...
    ...
    ...

    }

在你的宣言中你应该有android:configChanges="keyboardHidden|orientation"

然后它应该可以正常工作,就像在我的应用程序中一样。这是你在做什么的?

答案 1 :(得分:3)

// In your activity code.
int mCurrentOrientation;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mfo_offers);
    ........
    mCurrentOrientation = getCurrentOrientation();
}
@Override    
public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // You may handle different configuration changes in your activity which configured in your mainfest.xml, you only need to recreate layout when orientation changes.
        if(mCurrentOrientation != newConfig.orientation) {          
            recreate(); // This recreate the activity if you can properly restore your activity state.  
        }
        ......
}

请参阅此处的Activity.recreate():http://developer.android.com/reference/android/app/Activity.html#recreate()