在 OnLayoutChangeListener 中更改视图的大小

Changing the size of a view in OnLayoutChangeListener

我已经使用 recyclerview 实现了一个画廊,并且我已经向 viewholder 添加了一个 onLayoutChangeListener,这样一旦计算出布局,imageview 的高度就会改变以匹配图像的纵横比。首次打开 activity、旋转设备或解锁屏幕时它工作正常,但当从另一个 activity 返回时它不起作用。该方法已执行,但 imageview 没有改变。知道是什么原因造成的吗?

        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);
            }
        });

调试器显示设置的高度正确,但显示的图像视图不是应有的高度。

Correct Image

Incorrect Image

您似乎只是想在 ImageView 上获得正确的纵横比。

ImageView 有一个名为 adjustViewBounds 的 属性。如果您有特定的 layout_width,例如 match_parentdp 值,您可以为 layout_height 指定 wrap_content 并设置 android:adjustViewBounds="true"。这将导致 ImageView 在测量高度时自动考虑图像的纵横比。