【问题标题】:Set ImageView Size Programmatically in DP Java [duplicate]在 DP Java 中以编程方式设置 ImageView 大小 [重复]
【发布时间】:2016-06-18 14:48:24
【问题描述】:

我想在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 方法并将HorizontalScrollView 填充为ImageViews 包含在LinearLayouts 中。我需要在 DP 而不是像素中设置这个高度,以便它在所有设备上看起来都一样!!!

【问题讨论】:

    标签: java android xml android-layout imageview


    【解决方案1】:

    你需要将你的值转换为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 版本

    转换成Px的函数在kotlin中可以这样写(作为扩展)

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

    然后可以这样使用:

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

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2012-09-08
      • 2015-04-18
      • 1970-01-01
      相关资源
      最近更新 更多