When android calculate width and height of views

不想你离开。 提交于 2020-07-09 07:00:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!