Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the size of a view in OnLayoutChangeListener

I've implemented a gallery using the recyclerview and I've added an onLayoutChangeListener to the viewholder so that once the layout is calculated, the height of the imageview is changed to match the image's aspect ratio. It works fine when first opening the activity, rotating the device or unlocking the screen, but when coming back from another activity it doesn't work. The method is executed, but the imageview does not change. Any idea of what could be causing this?

        image.addOnLayoutChangeListener(new View.OnLayoutChangeListener(){
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                ImageView img = (ImageView) v;
                Bitmap bm = ((BitmapDrawable) img.getDrawable()).getBitmap();
                img.getLayoutParams().height = Utils.scaledHeight(bm.getWidth(), bm.getHeight(), img.getWidth());
                img.removeOnLayoutChangeListener(this);
            }
        });

The debugger shows the correct height being set, but the displayed imageview is not what it should be.

Correct Image

Incorrect Image

like image 270
Yujin Kang Avatar asked Nov 10 '22 04:11

Yujin Kang


1 Answers

It looks as though you're just trying to get the proper aspect ratio on an ImageView.

ImageView has a property called adjustViewBounds. If you have a specific layout_width like match_parent or a dp value, you can specify wrap_content for the layout_height and set android:adjustViewBounds="true". This will cause the ImageView to automatically respect the aspect ratio of the image when measuring for the height.

like image 82
kris larson Avatar answered Nov 14 '22 21:11

kris larson