Reputation: 221
I have a problem, and I can't seem to figure out what to do about it. I'm new to developing with Android, but I have experience with Java.
During the onCreate(bundle), onPostCreate(bundle) or any other similar method, I can't get the correct width of a View. It returns 0. I also made a simple button for debug purposses, and that button returns the correct value.
How do I call a method that gets the width of a View after the onCreate method? If that's not possible, what is a workaround?
Thanks in advance,
Gerralt
Upvotes: 0
Views: 124
Reputation: 5759
Do this is onWindowFocusChanged() like this:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus && llfullscreen!=null){
int layoutHeight = llfullscreen.getHeight();
ViewGroup.LayoutParams params = lv.getLayoutParams();
params.height = lv/2; //Set to half the screens size
this.lv.setLayoutParams(params);
this.lv.invalidate();
}
}
Upvotes: 0
Reputation: 54322
The problem is because, you are trying to find out the width as soon as you you start your activity.
But at this position the actual transformation of your view wouldn't have occurred. Android provides a special callback to find the width and height of all individual views. To access it, you have to override the onWindowFoucsChanged()
method. Here is a sample,
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
System.out.println("...Height..."+textview.getMeasuredWidth());
}
This line textview.getMeasuredWidth()
helps you to find the actual width of the textView at runtime. Similarly you can find the width and height for any view using this method.
Upvotes: 2
Reputation: 1617
As i think, you are in the onCreate(Bundle) method:
public void onCreate(Bundle xxx) {
super(xxx);
// init some stuff here
setContentView(R.layout.my_layout);
// from THIS point you can get sizes of Views
}
Sorry if i'm wrong, but on my project it works. OK, i have to say i use often custom views and use sizes not in my activity code but in View code.
Upvotes: 0