简体   繁体   中英

Call requires API level 16 (current min is 10): android.widget.ImageView#getMaxWidth

I created an ImageView with a fixed image ratio. Therefore I need android.widget.ImageView#getMaxWidth . By converting my code to be Android 10 compatible I can't use this functionality. What would be a workaround to geht the max width/height of the image view?

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int w, h; 
    if (getDrawable() == null) {
        w = h = 0;
    } else {
        w = getDrawable().getIntrinsicWidth();
        h = getDrawable().getIntrinsicHeight();
    }

    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);

    boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
    boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;

    int wPadding = getPaddingLeft() + getPaddingRight();
    int hPadding = getPaddingTop() + getPaddingBottom();

    int widthSize = resolveAdjustedSize(w + wPadding, getMaxWidth(), widthMeasureSpec);
    int heightSize = resolveAdjustedSize(h + hPadding, getMaxHeight(), heightMeasureSpec);

    float actualRatio = (float) (widthSize - wPadding) / (heightSize - hPadding);
    if (Math.abs(actualRatio - ratio) > 0.0000001) {
        boolean done = false;
        if (resizeWidth) {
            int newWidth = (int) ((heightSize - hPadding) / ratio) + wPadding;
            widthSize = resolveAdjustedSize(newWidth, getMaxWidth(), widthMeasureSpec);
        } else if (!done && resizeHeight) {
            int newHeight = (int) ((widthSize - wPadding) * ratio) + hPadding;
            heightSize = resolveAdjustedSize(newHeight, getMaxHeight(), heightMeasureSpec);
        }
    }


    setMeasuredDimension(widthSize, heightSize);
}

OK, here is what I did. To keep track of the image max width/height I overrid the setter for the properties. Only the setter is used to write these properties.

private int mMaxWidth = Integer.MAX_VALUE;
private int mMaxHeight = Integer.MAX_VALUE;

@Override
public void setMaxHeight(int maxHeight) {
    mMaxHeight = maxHeight;
    super.setMaxHeight(maxHeight);
}

@Override
public void setMaxWidth(int maxWidth) {
    mMaxWidth = maxWidth;
    super.setMaxWidth(maxWidth);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM