0

How to get max-width and max-Height for ImageView According to device density and screen size in Android

i'm using this

 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    try {
        Drawable drawable = getDrawable();

        if (drawable == null) {
            setMeasuredDimension(0, 0);
        } else {
            int width = (MeasureSpec.getSize(widthMeasureSpec))/4;
            int height = (width * drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth());
            setMeasuredDimension(width, height);
        }
    } catch (Exception e) {
        isMeasured = false;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
Anil M H
  • 3,332
  • 5
  • 34
  • 51

1 Answers1

0

You seem to have misunderstood the way that Android layouts work. Basically views get assigned a size by their parents. onMeasure allows the view to influence the size, but must follow the method contract.

In particular your onMeasure does not take into account the measure mode (both horizontal and vertical). You need to provide a measurement for all nine possible states:

horiz exactly, vertical exactly : set the size to what was passed in (should be last invocation)

horiz exactly, vertical at most : set the size horizontally to the given value, vertically set the value that is at most the given value (stretching with aspect ratio may make this smaller)

horiz exactly, vertical unspecified : set the horizontal size to the one given, set the vertical size to the best corresponding size (for example maintaining aspect ratio)

horiz at most, vertical exactly : set the vertical size to the given size. Set the horizontal size to an appropriate size that is at most the given horizontal size.

horiz at most, vertical at most : Find which dimension bounds the image according to the aspect ratio. Treat that dimension as if it was given exactly (but if the image is smaller than the bounds you may also use that instead)

horiz at most, vertical unspecified : If the horizontal size is smaller than the image treat it as if that size was given for the exact horizontal dimension, otherwise treat it as if the horizontal constraint was exact.

horiz unspecified, vertical exact : Like horiz exact, vertical unspecified, but horiz and vertical swapped

horiz unspecified, vertical at most : Like horiz at most, vertical unspecified, but horiz and vertical swapped

horiz unspecified, vertical unspecified : The intrinsic size of the image or some default if the image is not given (the default uses 100,100), using 0,0 makes the layout editor awkward.

Btw. Don't catch Exception, that is poor practice.

Community
  • 1
  • 1
Paul de Vrieze
  • 4,888
  • 1
  • 24
  • 29