NullPointerException
NullPointerException

Reputation: 37577

ImageView CENTER_CROP dont work

Welcome all.

i have a LinearLayout that must show a ImageView. The imageView must fit all the width of the LinearLayout, so i used match_parent for the width, and it must keep the aspect ratio, so i used wrap_content for the height and setAdjustViewBounds to true. But something is not working because the width of the ImageView is correct (it fits the width of the linear layout) but the height of the imageView is wrong (the image is being cutted in the upper and the lower part)

I tryed with all the scale types (fit_center, fit_xy, center_crop, center_inside etc...) and i have problems with all of them (for example, if i use fit_center, the image is does not fit the full width of the ImageView, i can see two black spaces on left and right of the image, also i tried using FIT_CENTER without setAdjustViewBounds and i have the same problem)

HERE YOU HAVE AN SNAPSHOT: https://i.sstatic.net/8hrKF.png

this is my code:

LinearLayout onlineHolder = this.holders.get(i);
onlineHolder.setLayoutParams(
    new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
onlineHolder.removeAllViews();
ImageView imgv = new ImageView(onlineHolder.getContext());
imgv.setLayoutParams(
    new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
imgv.setAdjustViewBounds(true);
imgv.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap b=res.getCachedBitmapWithWidth(this.width); //obtenemos el recurso cacheado con el width correspondiente
imageElement.setBitmap(b);
imgv.setImageBitmap(b);
onlineHolder.addView(imgv);

Thanks

EDIT: it only works if i specify the width and the height of the imageview with absolute numbers. For example, if i put 400 (400 is the 50% of the screen, the layout width) width and 583 height, it works, but if i put MATCH_PARENT for width and WRAP CONTENT for height... it not works... why?

Upvotes: 0

Views: 326

Answers (1)

osayilgan
osayilgan

Reputation: 5893

I have this one in XML and it works in the way you want. take a look.

<ImageView 
    android:id="@+id/attachedImage"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true" />

But if you want to do it on the runtime, I suggest to create an XML this way and inflate the View on the runTime and add it to your parent layout. That will work for sure.

EDIT : How to inflate the ImageView.

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.your_layout_contains_image_view, null, false);
ImageView imageView = view.findViewById(R.id.attachedImage);

Upvotes: 1

Related Questions