getWidth() returns 0 if set by android:layout_width=“match_parent”

前端 未结 2 975
日久生厌
日久生厌 2020-12-09 17:46

I have a class called FractalView that extends ImageView. My goal is to draw a fractal with this class that has the size of the whole screen. It is the only View in my activ

2条回答
  •  一生所求
    2020-12-09 18:28

    A view's size isn't available until after onMeasure(), particularly if its set to wrap_content, or fill_parent.

    You should either access the size in or after onMeasure() in the View code, or in a a Layout Tree Observer:

    LinearLayout layout = (LinearLayout)findViewById(R.id.mylayout);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 
    
        } 
    });
    

    You will also need to add android:id="@+id/mylayout" to your LinearLayout for the second one to work.

提交回复
热议问题