0

In my activity onCreate() method I created a View and hardcoded its width and height to be equal to 50. Then I call measure method. After that I expect that getMeasuredWidth() returns 50. But it returns 0.

    View v = new View(this);
    v.setLayoutParams(new ViewGroup.LayoutParams(50, 50));

    final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    v.measure(spec, spec);
    final int w = v.getMeasuredWidth();
    Log.e("aaa", String.valueOf(w)); // output is 0

What am I doing wrong? How can I force to calculate measured view's size? I do not want until it has been drawn, etc.

Nick
  • 3,205
  • 9
  • 57
  • 108

1 Answers1

3
private void measureDimension() {
    view.post(new Runnable() {
        @Override
        public void run() {
            int height = view.getMeasuredHeight();
            int width = view.getMeasuredWidth();

        }
    });
}

You can call this method in onCreate.

Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
Ganesh Kanna
  • 2,269
  • 1
  • 19
  • 29