How to get NEW width/height of root layout in onConfigurationChanged?

只谈情不闲聊 提交于 2019-12-02 19:08:58

getWidth() returns the width as the View is laid out, meaning you need to wait until it is drawn to the screen. onConfigurationChanged is called before redrawing the view for the new configuration and so I don't think you'll be able to get your new width until later.

For those looking for a more detailed solution description: You can use the ViewTreeObserver of your view and register an OnGlobalLayoutListener.

@Override
public void onConfigurationChanged(Configuration newConfiguration) {
    super.onConfigurationChanged(newConfiguration);
    final View view = findViewById(R.id.scrollview);

    ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            Log.v(TAG,
                    String.format("new width=%d; new height=%d", view.getWidth(),
                            view.getHeight()));
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
}

When onGlobalLayout called it's not sure that the view has been resized accordingly to the new layout orientation, so for me only the below solution worked properly:

@Override
public void onConfigurationChanged(Configuration newConfig) {
final int oldHeight = mView.getHeight();
final int oldWidth = mView.getWidth();

mView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (mView.getHeight() != oldHeight && mView.getWidth() != oldWidth) {
                mView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                //mView now has the correct dimensions, continue with your stuff
            }
        }
    });
    super.onConfigurationChanged(newConfig);}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!