Unable to figure out how to get a view / layout of width / height

I am new to Android. This should be the easiest thing in the world, but figuring it out is confusing: how do I get the dimensions of a view or layout?

The standard approach seems to be something like:

((LinearLayout) this.findViewById (R.id.MyLayout)) GetWidth () ;.

Except that it always returns zero, since I try to do this when the activity starts (onCreate) and the geometry is not set yet. I tried to include the sleeping places to give him the opportunity to customize the layout, except that he would not customize the layout until onCreate returned. So this is clearly not threaded .: P

I found a bunch of pages talking about overriding all kinds of different callback functions to make sure the layout loads when getWidth is called - but they all threw errors when I tried to put overrides in my activity, so I can assume that they were inverse calls to measure layouts and / or views. The problem is that I do not use custom view / layout classes - only standard ones. As far as I know, I can't just add an override.

Does anyone know what I should do? I spent something like 8 hours on this problem and received nothing. And that’s what usually such a trivial thing to do in most development environments!

+3
source share
5 answers
final View view = .....; // your view view.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // make sure it is not called anymore view.getViewTreeObserver().removeGlobalOnLayoutListener(this); // your code to get dimensions of the view here: // ... } }); 
+21
source

Why not View.getLayoutParams() ? It has public int height and public int width .

+1
source

Two years late, but putting him here for others. Try overriding onWindowFocusChanged. You should be able to get the measured width / height of the image.

+1
source

How about doing durring onStart() ? This method is called after onCreate() , which means the layout has been overestimated. Android life cycle

0
source

I have a job where I use:

 view.postDelayed(new MyRunnable(), 500); 

which runs the logic in MyRunnable 500 ms from now on. This allows you to use the CreateCreate method or any other lifecycle method to return and draw, so that I can get the correct height and width. But it is also ugly, as the user can see the delay.

-1
source

Source: https://habr.com/ru/post/1347923/


All Articles