Reputation: 9361
this code is used to show the width and height of the contentview and the code is run after the setContentView() method is called in the onCreate() method, but it results of a width of zero and height of zero. However the contentview opens up on the screen and it is not 0 for either width or height. What is wrong here and how to show the width and height of the contentview?
the contentview object is not null, I used a toString() statement to check that.
if this is not good then is there a better way to get the height and width of the contentView in pixles?
ViewGroup contentViewObj;
View v;
...
@Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
//v = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
v = (View) getWindow().getDecorView().findViewById(android.R.id.content);
Toast.makeText(MainActivity.this, "width of contentview " + v.getWidth()
+ " " + "height of contentView " + v.getHeight(), Toast.LENGTH_SHORT).show();
}
Upvotes: 1
Views: 1034
Reputation: 7708
The reason you get 0
is because the view has not been measured yet. To get the size of a layout, your should be using getWidth()
or getMeasuredWidth()
methods. However, these methods won't give you a meaningful answer until the view has been measured. Read about how android draws views here.
You can get the correct size, by overriding the onWindowFocusChanged()
as mentioned in this thread.
Alternatively, you could do this:
@Override
public void onContentChanged() {
super.onContentChanged();
v = (View) getWindow().getDecorView().findViewById(android.R.id.content);
v.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "width of contentview " + v.getWidth()
+ " " + "height of contentView " + v.getHeight(), Toast.LENGTH_SHORT).show();
}
});
}
Upvotes: 2
Reputation: 5295
You need to wait for the view to form/open completely, then you will get these values.Currently what happens is that your view is currently forming so that is why it is coming 0. You need to put some timer or handler such that this code will run after 2 ,3 seconds after your view has formed
Upvotes: 1