Ollie C
Ollie C

Reputation: 28509

How to access a view's dimensions from an Activity?

Accessing myView.getWidth() and getHeight() always return zero, and I understand this is because I'm calling them too early, before the views have been laid out.

But how CAN I access the size of views from an activity? I can't see a method to override and the docs aren't suggesting a lifecycle event I can catch.

===================================

Thanks Tanner. Here's the code I used, which works fine.

LinearLayout root = (LinearLayout)findViewById(R.id.main);
Display d = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = d.getWidth();
int screenHeight = d.getHeight();
root.measure(screenWidth, screenHeight);
View myView = findViewById(R.id.myView);
int width = myView.getMeasuredWidth();

Upvotes: 0

Views: 128

Answers (2)

Tanner Perrien
Tanner Perrien

Reputation: 3133

Have a look at this: http://developer.android.com/guide/topics/ui/how-android-draws.html

Have you tried calling measure() and then getMeasuredWidth() on your view?

Notice there is also the method requestLayout()

Upvotes: 1

woodshy
woodshy

Reputation: 4111

You should access dimensins after your layout was set as content view of activity. Just find it by id using findViewById(id) and then call myView.getWidth()

Upvotes: 0

Related Questions