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
  • 2,905
  • 8
  • 55
  • 100

1 Answers1

2
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,561
  • 4
  • 19
  • 27
Ganesh Kanna
  • 2,180
  • 18
  • 29