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

前端 未结 2 974
日久生厌
日久生厌 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:27

    I figured out a way to do this while I was typing the question. Instead of trying to retrieve the size in the constructor method, I moved the code to the onDraw() method like this:

    private void init() {
    
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        mScrWidth = canvas.getWidth();
        mScrHeight = canvas.getHeight();
        [...]
    }
    

    This returns correct dimensions.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题