Aakash Anuj
Aakash Anuj

Reputation: 3871

Extending a view which overrides onMeasure()

I have a view view1 which extends FrameLayout and overrides onMeasure() like this, so that it is rendered as a square:

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
  }

Now I want to create another view view2 which extends view1, but now I want view2 to have a height equal to the parent, and hence to cover the full screen. As of now, I get it as a square too.

How do I achieve this?

Upvotes: 0

Views: 713

Answers (2)

AL.
AL.

Reputation: 37798

Since the onMeasure for Square was already overridden where it disregards the height passed to it, as per your code:

@Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
  }

One way to do what you want -- view2 which extends view1, but now I want view2 to have a height equal to the parent, and hence to cover the full screen -- is to also override onMeasure of view2 calling on setDimension like this...

public class Square2 extends Square {

    public Square2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }
}

Here is a sample after I tried it out. (For code in Square View, I just copied your code in onMeasure).

Using Square: enter image description here

For Squre2:

enter image description here

Hope this helps.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317712

In view 1:

private boolean measureAsSquare = true;

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (measureAsSquare) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
    else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

public void setMeasureAsSquare(boolean b) {
    measureAsSquare = b;
}

In View2 constructor that subclasses view 1:

public View2(Context c) {
    setMeasureAsSquare(false);
}

Then you can use normal layout weight and height for view 2 to assign its preferred size.

Upvotes: 1

Related Questions