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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With