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
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.
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.