【问题标题】:onConfigurationChanged-it's still showing the first layoutonConfigurationChanged - 它仍然显示第一个布局
【发布时间】:2015-03-23 07:02:25
【问题描述】:

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

如果我删除 android:configChanges="orientation",它应该可以工作,但我需要处理 onConfigurationChanged。我应该怎么办??

【问题讨论】:

    标签: android android-manifest


    【解决方案1】:

    如果您在/res/layout 中有纵向布局main.xml,在/res/layout-land 中有横向布局main.xml,并且您的onConfigurationChanged() 看起来像这样:

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

    在你的清单中你应该有android:configChanges="keyboardHidden|orientation"

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

    【讨论】:

    • 是的,它工作得很好:))谢谢...我想问一下,为什么我们要写keyboardHidden??
    • 我认为是因为在某些设备上,当有人滑动打开键盘时,也会自动改变方向。
    • 你能帮帮我吗?它不适合我。我在不同的文件夹中有两个不同的 xml 文件。我添加了 android:configChanges="keyboardHidden|orientation" 以及您的代码格式,但它不起作用,
    • 我正在夸大布局,它一直让我崩溃。我什至没有意识到我所有问题的解决方案都在一行中。
    【解决方案2】:
    // 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()

    【讨论】:

    • public void recreate () (在 API 级别 11 中添加)导致使用新实例重新创建此 Activity。这导致与由于配置更改而创建 Activity 时的流程基本相同——当前实例将经历其生命周期到 onDestroy() 并在其之后创建一个新实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多