XML在设备方向改变时没有切换。

22
我创建了两个文件夹,res/layoutres/layout-land我得到的输出:
如果我在portrait模式下启动应用程序,则始终使用位于layout文件夹中的xml文件。并且如果我将设备更改为landscape模式,则不会使用layout-land中的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个回答

44

清单代码

android:configChanges="orientation|screenSize"

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


4
你知道我们如何检测屏幕方向是否改变吗?如果没有这个设置,onConfigurationChange 就不会被调用。 - Patrick
1
你对我来说是救命稻草! :) - Rohit TP

24

android:configChanges="orientation" 可以防止活动重新启动,因此也可以防止重新加载xml布局(通常在onCreate中执行)。 相反,会调用onConfigurationChanged(newConfig)方法。 因此,您可以执行以下操作:

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

如果可用,这将重新从layout-land目录中重新加载布局。 注意:您还需要将操作与按钮等内容链接起来。


5
如果我有碎片,怎么办? - PriyankaChauhan

2

不要忘记打开 设置 -> 显示 -> 自动旋转屏幕 选项。


1
问题不在于屏幕根本无法旋转,而在于布局没有改变。 - Riot Goes Woof
@Zorpix 你不可能知道作者的意思。我忘记在设置中启用“自动旋转”,这就是为什么我写了这个答案。 - kolobok
我并不是要粗鲁地否定你的回答。我知道像忘记打开自动旋转这样的小错误是会发生的。但这并不会导致方向改变而不改变XML,就像原问题所述。 - Riot Goes Woof
哦天啊,这实际上是我的问题的解决方案。因此,即使它没有解决原始问题,为了谷歌的缘故,我会保留这个答案。 - wessel

1
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);
        }            
    }
}

2
不要只贴一段代码,还请解释为什么这段代码可以解决所提出的问题。没有解释,这不是一个答案。 - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接