问题
I create my hierarchy of views by code, and then I do setContentView()
in the Activity with my root view like argument.
I need know width and height of one view in runtime but if i do getWidth()
or getHeight()
, i get 0. If i wait a few seconds i get the correct width or height.
I only want to know in what moment android calculate width / height of views. My code isn't outstanding
Thanks!
回答1:
This is because in onCreate()
the layouts haven't been calculated yet. So you need to add a GlobalLayoutListener
to know when layouts has been calculated and placed in screen.
final View view = findViewById(R.id.root);
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver vto = view.getViewTreeObserver();
vto.removeGlobalOnLayoutListener(this);
}
});
Where root is the root layout (LinearLayout, RelativeLayout i.e). Assign your root layout with the @+id/root.
回答2:
You don't say where you are trying to measure the view but my guess is it's in onCreate() or onResume()>
Try this in your onCreate().
// set a global layout listener which will be called when the layout pass is completed and the view is drawn
mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
// measure your views here
}
}
Here, mainLayout is a reference to the root view group of the layout.
This will also be called if the layout is resized after it's first drawn (views added in code, orientation changes etc) so you will always get the correct values.
回答3:
You can use some View class. add this :
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super(w,h,oldw,oldh);
if(oldw == 0 && w !=0){
...
// w and h is what you want
}
回答4:
For clarity, according to this Android documentation
When an Activity receives focus, it will be requested to draw its layout.
...and also measure view dimensions.
Focus receives after onResume
and lose it after onPause
method.
来源:https://stackoverflow.com/questions/17085392/when-android-calculate-width-and-height-of-views