CoDe
CoDe

Reputation: 11146

Wrong View Height/Width value on Orientation change?

I implemented onConfigurationChnage(..) to read value of view height and width on orientation configuration chnage

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;

        Log.i(TAG, "onConfigurationChanged: "+newConfig.orientation+", "+height+", "+width + ", "+mTempeFrameLayout.getWidth());
    }

but it always reply old value, if orientation get change it gave last orientation (probably)value.

Screen width/height using displaymetrics is coming right properly but same is not working for any view.

Any one have idea..how can get correct value on orientation Change?

Upvotes: 8

Views: 6192

Answers (2)

Lucid Dev Team
Lucid Dev Team

Reputation: 641

I had to use

@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);

        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                configHome();
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

  }
}

because the above answer was not working for me

Upvotes: 0

nitesh goel
nitesh goel

Reputation: 6406

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.

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

Upvotes: 18

Related Questions