Home » Android » android – How to find the Width of the a view before the view is displayed?

android – How to find the Width of the a view before the view is displayed?

Posted by: admin April 23, 2020 Leave a comment


How to find the Width of the a view before the view is displayed? I do not want to add a custom view and tap the dimensions in the OnChanged().

How to&Answers:
Display display = getWindowManager().getDefaultDisplay();
View view = findViewById(R.id.YOUR_VIEW_ID);
view.measure(display.getWidth(), display.getHeight());

view.getMeasuredWidth(); // view width
view.getMeasuredHeight(); //view height


@dmytrodanylyk — I think it will return width & height as 0 so you need to use following thing

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View contentview = inflater.inflate(R.layout.YOURLAYOUTNAME, null, false);
contentview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = contentview.getMeasuredWidth();
int height = contentview.getMeasuredHeight();

It will give you right height & width.


You should use OnGlobalLayoutListener which is called for changes on the view, but before it is drawn.

costumView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    public void onGlobalLayout() {




Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
view.measure(size.x, size.y);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();


I like to use this technique as per my answer on a related question:

Post a runnable from onCreate() that will be executed when the view has been created:

    contentView = findViewById(android.R.id.content);
    contentView.post(new Runnable()
        public void run()
            contentHeight = contentView.getHeight();

This code will run on the main UI thread, after onCreate() has finished.


This is the best way…… WORK!!!

public void onWindowFocusChanged(boolean hasFocus) {          

  if (fondo_iconos_height==0) { // to ensure that this does not happen more than once
      fondo_iconos_height = fondo_iconos.getHeight();