Reputation: 74
I have a class called game that extends View that is added to a LinearLayout. I know that it is displaying my View but i need to get the width and height of the view in order to draw some of my images. Here is my constructor code:
public Game(Activity activ)
{
activ.setContentView(R.layout.game);
...
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
setLayoutParams(lp);
layout = (LinearLayout)activ.findViewById(R.id.game_layout);
layout.addView(this);
...
}
now when i do this.getWidth() and this.getHeight() i keep getting a return value of 0. How can i get the width and the height of my view?
Upvotes: 0
Views: 1324
Reputation: 31789
I answered a similar question today. Try that. It should work.
Android - getting the width of a button which is set to wrap_content
Upvotes: 2
Reputation: 14600
The View class has both a getHeight() and getWidth method:
http://developer.android.com/reference/android/view/View.html#getHeight() http://developer.android.com/reference/android/view/View.html#getWidth()
Here's a blog on the subject as well:
http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
Upvotes: 0
Reputation: 13830
You can use layout.getLayoutParams()
to get the layout param, and then use the height
attribute in it.
UPDATE: If you are getting zero value, it could also mean that the view has not been initialized yet.
Upvotes: 0