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().
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
Answer:
@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.
Answer:
You should use OnGlobalLayoutListener
which is called for changes on the view, but before it is drawn.
costumView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
costumView.getWidth();
}
});
Answer:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
view.measure(size.x, size.y);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
Answer:
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.
Answer:
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();
}
}
Tags: androidandroid, view