首页 > 解决方案 > Android ImageView 通过代码更改 maxHeight 属性

问题描述

我有一个可滚动的视图,我在其中以编程方式插入各种视图。有些视图是文本字段,有些是图像。

我插入的大多数图像都是水平图像,但有些图像是垂直的。对于垂直图像,我想以编程方式修改 ImageView 的 maxHeight 属性。所以我做了一个近似检查 if(height > (width * 1.3) )

这是我的 Imageview xml

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@null"
android:maxHeight="200dp"
android:scaleType="fitCenter" />

这是我的代码:

if (h > (1.3 * w)) {
    imageView.setMaxHeight(500);
}

但这不起作用。谁能告诉我为什么以及解决方案是什么?

标签: androidimageview

解决方案


由于您的值 500 是像素值。所以,我认为你需要将 500 转换为对应的 dp 值。尝试使用这个:

    private int dpToPx(int dp, Activity activity) {
        Resources r = activity.getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

并将您的代码更改为:

if (h > (1.3 * w)) {
    imageView.setMaxHeight(dpToPx(500, this));
}

推荐阅读