【问题标题】:The xml is not switching when device orientation change设备方向更改时 xml 不切换
【发布时间】:2011-05-31 11:32:11
【问题描述】:


我做了两个文件夹,res/layoutres/layout-land

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

我的期望是
它应该在纵向模式下使用 layout 文件夹中的 xml,在横向模式下使用 layout-land 中的 xml

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

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

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

【问题讨论】:

    标签: android configuration android-layout


    【解决方案1】:

    清单代码

    android:configChanges="orientation|screenSize"
    

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

    【讨论】:

    • 你知道在这种情况下我们如何检测方向变化吗?如果没有这个设置 onConfigurationChange 永远不会被调用。
    • 你是我的救星! :)
    【解决方案2】:

    android:configChanges="orientation" 阻止 Activity 重新启动,因此也阻止重新加载 xml 布局(通常在 onCreate 中执行此操作)。 相反, onConfigurationChanged(newConfig) 被调用。所以你可以这样做:

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

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

    【讨论】:

    • 如果我有碎片怎么办?
    【解决方案3】:
    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);
            }            
        }
    }
    

    【讨论】:

    • 不要只发布一段代码,请解释为什么这段代码可以解决所提出的问题。没有解释,这不是答案。
    【解决方案4】:

    别忘了打开Settings -&gt; Display -&gt; Auto-rotate screen选项。

    【讨论】:

    • 问题不在于屏幕根本不会旋转。问题是布局没有改变。
    • @Zorpix 你不知道作者的意思。我忘了在设置中启用“自动旋转”,这就是我写这个答案的原因。
    • 我并不是要粗鲁地驳回您的回答。我知道会发生诸如忘记打开自动旋转之类的失误。但这不会导致方向改变,但不会像原始问题所述那样改变 XML。
    • 天哪,这实际上是我的问题的解决方案。因此,即使它没有解决原始问题的问题,为了谷歌的缘故,我也会保留这个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多