当设备方向改变时,xml不会切换

时间:2010-12-28 07:57:35

标签: android configuration android-layout


我创建了两个文件夹res/layoutres/layout-land

我得到的输出
如果我以portrait模式启动应用程序,如果应用程序以layout模式运行,它将始终使用portrait文件夹中的xml。如果我将设备更改为layout-land模式,则不会在landscape中使用xml 如果它以landscape模式启动,则仅使用layout-land中的xml 当方向更改

时,xml不会切换

我的期望
当它处于纵向模式时应该使用layout文件夹中的xml,并且在横向模式下使用layout-land中的xml

在清单文件中,我为活动添加了android:configChanges="orientation"

<supports-screens 
        android:resizeable="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:anyDensity="true" />

我在这里错过了什么吗?我需要做些什么改变?
谢谢

4 个答案:

答案 0 :(得分:37)

清单代码

android:configChanges="orientation|screenSize"

忽略“layout-land”中的XML并使用“layout”文件夹中的XML。如果您为横向创建不同的XML ,请使用该活动的android:configChanges="orientation|screenSize"标记。

答案 1 :(得分:22)

android:configChanges =“orientation”会阻止活动重新启动,因此重新加载xml布局(通常在onCreate中执行此操作)。 而是调用onConfigurationChanged(newConfig)。所以你可以这样做:

@Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.<xml file>);
    }

如果可以的话,这将从layout-land目录重新加载布局。 注意:您还需要将操作链接到按钮和类似的东西

答案 2 :(得分:2)

private void setContentBasedOnLayout()
{
    WindowManager winMan = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);

    if (winMan != null)
    {
        int orientation = winMan.getDefaultDisplay().getOrientation();

        if (orientation == 0) {
            // Portrait
            setContentView(R.layout.alertdialogportrait);
        }
        else if (orientation == 1) {
            // Landscape
            setContentView(R.layout.alertdialoglandscape);
        }            
    }
}

答案 3 :(得分:2)

不要忘记打开Settings -> Display -> Auto-rotate screen选项。

相关问题