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().
6 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 4 Comments
Joru
You might also keep in mind that if the view isn't inflated it's width and height will be 0.
Pavankumar Vijapur
You are right Joru. I used the ViewTreeObserver and resolved my issue. Thanks to all who tried to answer.
jcaruso
view.measure(display.getWidth(), display.getHeight()) is deprecated
Hrishikesh Kadam
view.measure takes View.MeasureSpec as an arguments. @Sandip Jadhav's answer is up to date.
@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.
2 Comments
CrandellWS
That is what I need to determine if I should start a new row of checkboxes, first making it a single line and then prevent overflow by calculating the width...perfect thank you. coming from -> stackoverflow.com/a/24054428/1815624
qix
Yes, this is a handy way to figure out the intrinsic size of a view based on its initial xml layout, and useful if say you're doing some dynamic calculations later on for layouts.
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.
Comments
This is the best way...... WORK!!!
public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (fondo_iconos_height==0) { // to ensure that this does not happen more than once fondo_iconos.getLocationOnScreen(loc); fondo_iconos_height = fondo_iconos.getHeight(); redraw_function(); } }