以Java编程方式设置ImageView尺寸(单位为DP)

5

我想在Android中设置一个ImageView的宽度和高度。这个ImageViewXML中不存在,是在这里创建的:

public void setImageView(int i,Integer d, LinearLayout layout ) {
    ImageView imageView = new ImageView(this);
    imageView.setId(i);
    imageView.setPadding(2, 2, 2, 2);
    imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), d));
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    layout.addView(imageView);
}

并且它被放置在这个 LinearLayout 中:

<HorizontalScrollView
    android:id="@+id/horizontal_scroll_view"
    android:layout_width="fill_parent"
    android:layout_gravity="center"
    android:background="@drawable/white_lines"
    android:layout_weight="15"
    android:layout_height="0dp" >

    <LinearLayout
        android:id="@+id/scroll_view_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#999A9FA1"
        android:orientation="horizontal" >

    </LinearLayout>

</HorizontalScrollView>

所以基本上我多次调用setImageView方法,使用LinearLayouts包含ImageViews填充我的HorizontalScrollView。我需要将这个高度设置为DP而不是像素,以便在所有设备上看起来都一样!!!

1个回答

19

你需要将你的数值转换为dps,你可以使用以下函数来完成:

public static int dpToPx(int dp, Context context) {
    float density = context.getResources().getDisplayMetrics().density;
    return Math.round((float) dp * density);
}

然后,要将 ImageView 的大小设置为 px 值,可以这样做:

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)imageView.getLayoutParams();
params.width = dpToPx(45);
params.height = dpToPx(45);
imageView.setLayoutParams(params);

(将LinearLayout更改为您的ImageView所在的任何容器)

编辑:Kotlin版本

在Kotlin中,将转换为Px的函数可以编写为这样的扩展:

fun Int.toPx(context: Context) = this * context.resources.displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT

然后可以像这样使用它:

view.updateLayoutParams {
    width = 200.toPx(context)
    height = 100.toPx(context)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接