Set ImageView Size Programmatically in DP Java

时间:2016-03-04 18:20:46

标签: java android xml android-layout imageview

I want to set the width and height of an ImageView in Android. The ImageView does not exist in XML. It is created here:

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

And it is placed into this 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>

So essentially I call the setImageView method many times and fill my HorizontalScrollView with ImageViews enclosed in LinearLayouts. I need to set this height in DP not pixels so that it looks the same across all devices!!!

1 个答案:

答案 0 :(得分:5)

您需要将值转换为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