614

I am creating all of the elements in my android project dynamically. I am trying to get the width and height of a button so that I can rotate that button around. I am just trying to learn how to work with the android language. However, it returns 0.

I did some research and I saw that it needs to be done somewhere other than in the onCreate() method. If someone can give me an example of how to do it, that would be great.

Here is my current code:

package com.animation;

import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;

public class AnimateScreen extends Activity {


//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    LinearLayout ll = new LinearLayout(this);
    
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(30, 20, 30, 0);

    Button bt = new Button(this);
    bt.setText(String.valueOf(bt.getWidth()));
   
    RotateAnimation ra = new RotateAnimation(0,360,bt.getWidth() / 2,bt.getHeight() / 2);
    ra.setDuration(3000L);
    ra.setRepeatMode(Animation.RESTART);
    ra.setRepeatCount(Animation.INFINITE);
    ra.setInterpolator(new LinearInterpolator());

    bt.startAnimation(ra);
    
    ll.addView(bt,layoutParams);
    
    setContentView(ll);
}

28 Answers 28

986

The basic problem is, that you have to wait for the drawing phase for the actual measurements (especially with dynamic values like wrap_content or match_parent), but usually this phase hasn't been finished up to onResume(). So you need a workaround for waiting for this phase. There are different possible solutions to this:

1. Listen to Draw/Layout Events: ViewTreeObserver

A ViewTreeObserver gets fired for different drawing events. Usually the OnGlobalLayoutListener is what you want for getting the measurement, so the code in the listener will be called after the layout phase, so the measurements are ready:

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        view.getHeight(); //height is ready
    }
});

Note: The listener will be immediately removed because otherwise it will fire on every layout event. If you have to support apps SDK Level < 16 use this to unregister the listener:

public void removeGlobalOnLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim)

2. Add a runnable to the layout queue: View.post()

Not very well known and my favourite solution. Basically just use the View's post method with your own runnable. This basically queues your code after the view's measure, layout, etc. as stated by Romain Guy:

The UI event queue will process events in order. After setContentView() is invoked, the event queue will contain a message asking for a relayout, so anything you post to the queue will happen after the layout pass

Example:

final View view=...;
...
view.post(new Runnable() {
            @Override
            public void run() {
                view.getHeight(); //height is ready
            }
        });

The advantage over ViewTreeObserver:

  • your code is only executed once, and you don't have to disable the Observer after execution which can be a hassle
  • less verbose syntax

References:


3. Overwrite Views's onLayout Method

This is only practical in certain situation when the logic can be encapsulated in the view itself, otherwise this is a quite verbose and cumbersome syntax.

view = new View(this) {
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        view.getHeight(); //height is ready
    }
};

Also mind, that onLayout will be called many times, so be considerate what you do in the method, or disable your code after the first time

4. Check if has been through layout phase

If you have code that is executing multiple times while creating the UI you could use the following support v4 lib method:

View viewYouNeedHeightFrom = ...
...
if(ViewCompat.isLaidOut(viewYouNeedHeightFrom)) {
   viewYouNeedHeightFrom.getHeight();
}

Returns true if view has been through at least one layout since it was last attached to or detached from a window.

Additional: Getting statically defined measurements

If it suffices to just get the statically defined height/width, you can just do this with:

But mind you, that this might be different to the actual width/height after drawing. The Javadoc describes the difference in more detail:

The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.

The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent (see Layout for more details.) The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().

The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight().

13
  • 2
    I'm using the view.post in a fragment. I need to measure the view whose parent's height is 0dp and has a weight set. Everything I try returns a height of zero (I've also tried the global layout listener). When I put the view.post code in onViewCreated with a delay of 125, it works, but not without the delay. Ideas?
    – Psest328
    Jan 28, 2015 at 21:50
  • 10
    too bad you can only upvote an answer once, really good explanation. I had a problem with a view rotation if I quit my app and restarted it from the recent apps. If I swiped it from there and did a fresh restart everything was fine. The view.post() saved my day!
    – Matthias
    Jan 16, 2016 at 17:39
  • 1
    Thanks. I usually use View.post() (2nd method), but if it is called from a background thread it sometimes doesn't work. So, don't forget to write runOnUiThread(new Runnable() {...}. Currently I use a variation of the 1st method: addOnLayoutChangeListener. Don't forget to remove it then inside: removeOnLayoutChangeListener. It works from background thread as well.
    – CoolMind
    Aug 1, 2016 at 7:45
  • 3
    Unfortunately for me 'View.post()' is not working all the time. I have 2 projects which are very similar. In one project it's working, on the other is not working. :(. In both situation I call the method from 'onCreate()' method from an Activity. Any suggestion why? Sep 19, 2017 at 22:45
  • 4
    I find the issue. In one project the view has android:visibility="gone", and on the other project the visibility property wasinvisible. If the visibility is gone the width will be always 0. Sep 19, 2017 at 22:58
269

We can use

@Override
 public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  //Here you can get the size!
 }
6
  • 11
    so how can we work in Fragments ? this works only in Activity ? Jan 4, 2015 at 10:05
  • 10
    This should do the thing but its should not be the answer. A user wants to get dimensions in any point of time instead of getting drawn on the window. Also this method gets called multiple time or every time when there's a change(View hide, gone, adding new views etc..) in the window. So use it carefully :) Aug 20, 2015 at 12:47
  • 1
    This is a hack and it seems like using the ViewTreeObserver would be better.
    – i_am_jorf
    Nov 19, 2015 at 22:30
  • 1
    Don't mean to sound rude, but leaving an auto generated comment (especially in 2 lines of code) doesn't give much confidence that you actually know what you are doing.
    – Natix
    Feb 6, 2016 at 23:26
  • Unluckily, it didn't work for me. Trying viewTreeObserver worked for me. Mar 16, 2016 at 9:10
223

You are calling getWidth() too early. The UI has not been sized and laid out on the screen yet.

I doubt you want to be doing what you are doing, anyway -- widgets being animated do not change their clickable areas, and so the button will still respond to clicks in the original orientation regardless of how it has rotated.

That being said, you can use a dimension resource to define the button size, then reference that dimension resource from your layout file and your source code, to avoid this problem.

7
  • 88
    ngreenwood6, what is your other solution?
    – Andrew
    Feb 5, 2011 at 3:49
  • 12
    @Andrew - if you want negreenwood6 to be notified of your follow up, you have to start your message like I did to you (I think first three letters is enough) - CommonsWare gets notified automatically, since he wrote this response, but ngreen doesn't unless you address them. Nov 4, 2011 at 17:45
  • 11
    @Override public void onWindowFocusChanged(boolean hasFocus) { // TODO Auto-generated method stub super.onWindowFocusChanged(hasFocus); //Here you can get the size! }
    – Sana
    Apr 12, 2012 at 6:26
  • 5
    @ngreenwood6 So what was your solution?
    – starcodex
    Feb 27, 2014 at 5:35
  • 6
    Use this listener to get size, when is your screen ready. view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {} Nov 4, 2015 at 15:07
118

I used this solution, which I think is better than onWindowFocusChanged(). If you open a DialogFragment, then rotate the phone, onWindowFocusChanged will be called only when the user closes the dialog):

    yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once :
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // Here you can get the size :)
        }
    });

Edit : as removeGlobalOnLayoutListener is deprecated, you should now do :

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {

    // Ensure you call it only once :
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
    else {
        yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    // Here you can get the size :)
}
8
  • 4
    this is by far the best solution! because it works also on dynamic solutions where the width and height are not known and calculated. i.e. in a relative layout based on the positions/sizes of other elements. Well done! Aug 22, 2013 at 22:41
  • 2
    This requires API 16 or higher (Jelly bean)
    – tomsv
    Apr 21, 2014 at 11:57
  • 7
    It does NOT REQUIRE API 16! The only issue is method removeGlobalOnLayoutListener deprecated from API 16, but there is simple solution compatible with all api levels - stackoverflow.com/questions/16189525/…
    – gingo
    Jun 26, 2014 at 12:16
  • If you need to remove the listener so that doesn’t call itself many times and you having issues with different APIs, I recommend you to set a false boolean at the head of the class and then after capturing the values set it to true so that it doesn’t capture the values again. Jan 15, 2015 at 18:34
  • If you remove the listener after the first run you might get wrong dimensions: 02-14 10:18:53.786 15063-15063/PuzzleFragment: height: 1647 width: 996 02-14 10:18:53.985 15063-15063/PuzzleFragment: height: 1500 width: 996 Feb 14, 2016 at 9:23
91

If you need to get width of some widget before it is displayed on screen, you can use getMeasuredWidth() or getMeasuredHeight().

myImage.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = myImage.getMeasuredWidth();
int height = myImage.getMeasuredHeight();
8
  • 7
    For some reason, this was the only answer that worked for me - thanks! Jul 23, 2015 at 16:58
  • Same to me, the simplest solution, that worked to me
    – Tima
    Feb 21, 2017 at 21:02
  • Work like a charm! Aug 30, 2017 at 13:41
  • 2
    @CommonsWare how does this solution give the height and width before the view tree observer on global layouts callback, an explanation would be helpful. Jan 5, 2019 at 11:51
  • It's 2021 this method solved my problem
    – Zero
    Dec 5, 2021 at 9:56
76

As Ian states in this Android Developers thread:

Anyhow, the deal is that layout of the contents of a window happens after all the elements are constructed and added to their parent views. It has to be this way, because until you know what components a View contains, and what they contain, and so on, there's no sensible way you can lay it out.

Bottom line, if you call getWidth() etc. in a constructor, it will return zero. The procedure is to create all your view elements in the constructor, then wait for your View's onSizeChanged() method to be called -- that's when you first find out your real size, so that's when you set up the sizes of your GUI elements.

Be aware too that onSizeChanged() is sometimes called with parameters of zero -- check for this case, and return immediately (so you don't get a divide by zero when calculating your layout, etc.). Some time later it will be called with the real values.

4
  • 8
    onSizeChanged worked for me. onWindowFocusedChanged doesn't get called in my custom view. Feb 19, 2013 at 16:21
  • this looks a good solution, but what should i always create my custom view to override onSizeChanged method?
    – M.ElSaka
    Oct 17, 2013 at 12:13
  • Bottom line, if you call getWidth() etc. in a constructor, it will return zero. that's a bingo. The root of my issues. Nov 24, 2015 at 17:15
  • I suggest this solution for fragments, because some other solutions return 0 in my case.
    – WindRider
    Nov 27, 2015 at 16:52
35

I would rather use OnPreDrawListener() instead of addOnGlobalLayoutListener(), since it is called a bit earlier than other listeners.

    view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
    {
        @Override
        public boolean onPreDraw()
        {
            if (view.getViewTreeObserver().isAlive())
                view.getViewTreeObserver().removeOnPreDrawListener(this);
            
            // put your code here
            return true;
        }
    });

Adjusted the code according to comment of @Pang. onPreDraw method should return true to proceed with the current drawing pass.

1
33

AndroidX has multiple extension functions that help you with this kind of work, inside androidx.core.view

You need to use Kotlin for this.

The one that best fits here is doOnLayout:

Performs the given action when this view is laid out. If the view has been laid out and it has not requested a layout, the action will be performed straight away otherwise, the action will be performed after the view is next laid out.

The action will only be invoked once on the next layout and then removed.

In your example:

bt.doOnLayout {
    val ra = RotateAnimation(0,360,it.width / 2,it.height / 2)
    // more code
}

Dependency: androidx.core:core-ktx:1.0.0

3
  • 1
    This is the only correct answer. android.googlesource.com/platform/frameworks/support/+/…
    – hector6872
    Jan 21, 2020 at 12:48
  • 1
    these extensions are really important and useful
    – Ahmed na
    Mar 14, 2020 at 4:03
  • Thank you so much. it look like doOnLayout is better than addOnGlobalLayoutListener. In my case, I change the theme of application in a Fragment of ViewPager. After I changed the theme, addOnGlobalLayoutListener in onViewCreated of another Fragment fired and return 0. With doOnLayout, this problem won't happened. doOnLayout is not fired until I come back to the Fragment
    – Linh
    Jan 4, 2022 at 9:46
12

A Kotlin Extension to observe on the global layout and perform a given task when height is ready dynamically.

Usage:

view.height { Log.i("Info", "Here is your height:" + it) }

Implementation:

fun <T : View> T.height(function: (Int) -> Unit) {
    if (height == 0)
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                function(height)
            }
        })
    else function(height)
}
0
6

It happens because the view needs more time to be inflated. So instead of calling view.width and view.height on the main thread, you should use view.post { ... } to make sure that your view has already been inflated. In Kotlin:

view.post{width}
view.post{height}

In Java you can also call getWidth() and getHeight() methods in a Runnable and pass the Runnable to view.post() method.

view.post(new Runnable() {
        @Override
        public void run() {
            view.getWidth(); 
            view.getHeight();
        }
    });
3
  • 2
    This isn't correct answer as the view might not be measured and laid out when the posted code executes. It would be an edge case, but .post doesn't guarantee the view to be laid out.
    – d.aemon
    Mar 12, 2020 at 14:53
  • 1
    This answer was great and worked for me. Thank you very much Ehsan
    – MMG
    Apr 15, 2020 at 3:37
  • 1
    Be careful that getWidth() is measured in pixels, not dp. I lost too much time with this little detail May 8, 2021 at 12:11
5

One liner if you are using RxJava & RxBindings. Similar approach without the boilerplate. This also solves the hack to suppress warnings as in the answer by Tim Autin.

RxView.layoutChanges(yourView).take(1)
      .subscribe(aVoid -> {
           // width and height have been calculated here
      });

This is it. No need to be unsubscribe, even if never called.

0
5

Maybe this helps someone:

Create an extension function for the View class

filename: ViewExt.kt

fun View.afterLayout(what: () -> Unit) {
    if(isLaidOut) {
        what.invoke()
    } else {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                what.invoke()
            }
        })
    }
}

This can then be used on any view with:

view.afterLayout {
    do something with view.height
}
3

Height and width are zero because view has not been created by the time you are requesting it's height and width . One simplest solution is

view.post(new Runnable() {
        @Override
        public void run() {
            view.getHeight(); //height is ready
            view.getWidth(); //width is ready
        }
    });

This method is good as compared to other methods as it is short and crisp.

3

If you are using Kotlin

  customView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {

            override fun onGlobalLayout() {

                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                    customView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
                else {
                    customView.viewTreeObserver.removeGlobalOnLayoutListener(this)
                }

                // Here you can get the size :)
                viewWidth = customView.width
            }
        })
2

Answer with post is incorrect, because the size might not be recalculated.
Another important thing is that the view and all it ancestors must be visible. For that I use a property View.isShown.

Here is my kotlin function, that can be placed somewhere in utils:

fun View.onInitialized(onInit: () -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (isShown) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                onInit()
            }
        }
    })
}

And the usage is:

myView.onInitialized {
    Log.d(TAG, "width is: " + myView.width)
}
2

For Kotlin:

I have faced a production crash due to use view.height/ view.width which lead to NaN while I was using View.post() which sometimes view diemsions returned with 0 value.

So,

Use view.doOnPreDraw { // your action here} which is:

  • OneShotPreDrawListener so it called only one time.
  • Implements OnPreDrawListener which make sure view is layouted and measured
1

well , you can use addOnLayoutChangeListener

you can use it in onCreate in Activity or onCreateView in Fragment

@Edit dont forget to remove it because in some cases its trigger infinite loop


myView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener{
                override fun onLayoutChange(
                    v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int
                ) {
                    if (v?.width > 0 && v?.height > 0){
                        // do something
                        Log.i(TAG, "view : ${view.width}")
                        // remove after finish
                        v?.removeOnLayoutChangeListener(this) 
                    }
                }
            })

1

Cleanest way of doing this is using post method of view :

kotlin:

  view.post{
      var width = view.width
      var height = view.height
  }

Java:

view.post(new Runnable() {
    @Override
    public void run() {
        int width = view.getWidth();
        int height = view.getHeight();
    }
});
0

Gone views returns 0 as height if app in background. This my code (1oo% works)

fun View.postWithTreeObserver(postJob: (View, Int, Int) -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            measure(widthSpec, heightSpec)
            postJob(this@postWithTreeObserver, measuredWidth, measuredHeight)
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                @Suppress("DEPRECATION")
                viewTreeObserver.removeGlobalOnLayoutListener(this)
            } else {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}
0

We need to wait for view will be drawn. For this purpose use OnPreDrawListener. Kotlin example:

val preDrawListener = object : ViewTreeObserver.OnPreDrawListener {

                override fun onPreDraw(): Boolean {
                    view.viewTreeObserver.removeOnPreDrawListener(this)

                    // code which requires view size parameters

                    return true
                }
            }

            view.viewTreeObserver.addOnPreDrawListener(preDrawListener)
0

In my case, I can't get a view's height by post or by addOnGlobalLayoutListener, it's always 0. Because my view is in a fragment, and the fragment is the second tab in MainActivity. when I open MainActivity, I enter the first tab, so the second tab doesn't show on the screen. But onGlobalLayout() or post() function still has a callback.

I get the view's height when the second fragment is visible on the screen. And this time I get the correct height.

2
  • First, your answer is an own opinion. In addition, a good and accepted answer was given 8 years ago. Therefore, your answer is unnecessary. Jun 27, 2022 at 14:05
  • Thank you for your advice. I try to solve my problem with the above best answer. But it did not work. So I Offered another possibility.
    – Warm Man
    Jun 28, 2022 at 8:18
0

Usage:

imageView.size { width, height ->
            //your code
        }

View extention:


fun <T : View> T.size(function: (Int, Int) -> Unit) {
    if (isLaidOut && height != 0 && width != 0) {
        function(width, height)
    } else {
        if (height == 0 || width == 0) {
            var onLayoutChangeListener: View.OnLayoutChangeListener? = null
            var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null

            onGlobalLayoutListener = object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    if (isShown) {
                        removeOnLayoutChangeListener(onLayoutChangeListener)
                        viewTreeObserver.removeOnGlobalLayoutListener(this)
                        function(width, height)
                    }
                }
            }

            onLayoutChangeListener = object : View.OnLayoutChangeListener {
                override fun onLayoutChange(
                    v: View?,
                    left: Int,
                    top: Int,
                    right: Int,
                    bottom: Int,
                    oldLeft: Int,
                    oldTop: Int,
                    oldRight: Int,
                    oldBottom: Int
                ) {
                    val width = v?.width ?: 0
                    val height = v?.height ?: 0
                    if (width > 0 && height > 0) {
                        // remove after finish
                        viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
                        v?.removeOnLayoutChangeListener(this)
                        function(width, height)
                    }
                }
            }

            viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
            addOnLayoutChangeListener(onLayoutChangeListener)
        } else {
            function(width, height)
        }
    }
}

0
public final class ViewUtils {

    public interface ViewUtilsListener {
        void onDrawCompleted();
    }

    private ViewUtils() {
    }

    public static void onDraw(View view, ViewUtilsListener listener) {
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (view.getHeight() != 0 && view.getWidth() != 0) {
                    if (listener != null) {
                        listener.onDrawCompleted();
                    }
                    view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });
    }
}

you can use like this ;

ViewUtils.onDraw(view, new ViewUtils.ViewUtilsListener() {
                @Override
                public void onDrawCompleted() {
                    int width = view.getWidth();
                    int height = view.getHeight();
                }
            });
0
    private val getWidth: Int
    get() {
        if (Build.VERSION.SDK_INT >= 30) {
            val windowMetrics =windowManager.currentWindowMetrics
            val bounds = windowMetrics.bounds
            var adWidthPixels = View.width.toFloat()
            if (adWidthPixels == 0f) {
                adWidthPixels = bounds.width().toFloat()
            }
            val density = resources.displayMetrics.density
            val adWidth = (adWidthPixels / density).toInt()
            return adWidth
        } else {
            val display = windowManager.defaultDisplay
            val outMetrics = DisplayMetrics()
            display.getMetrics(outMetrics)
            val density = outMetrics.density
            var adWidthPixels = View.width.toFloat()
            if (adWidthPixels == 0f) {
                adWidthPixels = outMetrics.widthPixels.toFloat()
            }
            val adWidth = (adWidthPixels / density).toInt()
            return adWidth
        }
    }

replace (View) with the view you want to measure

0

Just came around this old question. Basically, the solution is to wait for the View to be measured and "drawn". You can achieve that by implementing some late lifecycle callback (e.g. onGlobalLayout), but I found a simpler solution that works well for me: just wait for the attributes to become non-zero.

The caveat here is that you mustn't block the UI thread while waitig. It's very easy to achieve if you use Kotlin Coroutines:

override fun onStart() {
        super.onStart()
       
        coroutineScope.launch {
            while (imgBarcode.width == 0 || imgBarcode.height == 0) {
                MyLogger.d("waiting for ImageView to get its eventual size")
                delay(50)
            }

            val barcodeBitmap = generateBarcodeUseCase.generateBarcode(
                data, imgBarcode.width, imgBarcode.height
            )

            imgBarcode.setImageBitmap(barcodeBitmap)
        }
    }

If you don't use Coroutines, you'll need to use e.g. Handler.postDelayed() calls to implement the same feature.

-1

This is a little old, but was having trouble with this myself (needing to animate objects in a fragment when it is created). This solution worked for me, I believe it is self explanatory.

class YourFragment: Fragment() {
    var width = 0
    var height = 0


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val root = inflater.inflate(R.layout.fragment_winner_splash, container, false)
    container?.width.let {
        if (it != null) {
            width = it
        }
    }
    container?.height.let {
        if (it != null) {
            height = it
        }
    }
    
    return root
}
 
-1

If you're worried about overworking the onDraw method, you can always set the dimension as null during construction and then only set the dimension inside of onDraw if it's null.

That way you're not really doing any work inside onDraw

class myView(context:Context,attr:AttributeSet?):View(context,attr){
var height:Float?=null


override fun onDraw(canvas:Canvas){
    if (height==null){height=this.height.toFloat()}
    }
}
-1
  1. Set layoutParams:

    view.layoutParams = ViewGroup.LayoutParams(0, 0)
    
  2. In the doOnLayout method you can get the size of the view:

    view.doOnLayout { view -> view.width | view.height }
    
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.