Custom drawable with height = 0.8 * bounds.width() when bounds.height it's wrap content

211 Views Asked by At

I created my custom drawable. And to draw it, I'm using the bounds. But, when the user use:

android:layout_width="match_parent"
android:layout_height="wrap_content"

I get bounds.height() == 1. Then, I want to use as height = 0.8 * bounds.width.

I tried it, because when the user use WRAP_CONTENT I get bounds.height() = 1. So then I set my drawable height to 0.8*width(). But I don't get the proper size. I just get like the height is 1. I read that you need to call invalidate(), but how do I call it, because if I call invalidate() in draw() then the method is called infinitely.

2

There are 2 best solutions below

0
Marcin Grabowski On

You should use onMeasure method.

Lifecycle call it when it's need to invalidate size of view you working on.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    ViewGroup.LayoutParams params = getLayoutParams();

    //height and width expected from wrap_content and match_parent
    int newHeight = MeasureSpec.getSize(heightMeasureSpec);
    int newWidth = MeasureSpec.getSize(widthMeasureSpec);
    int myHeight= newWidth * 0.8;

height = myHeight
    width = newWidth
}
0
thundertrick On

Consider using layout_constraintDimensionRatio of ConstraintLayout: Official Guide

Or u can also fix the size issue in onMeasure().