Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ImageView Size Programmatically in DP Java [duplicate]

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!!!

like image 543
Alk Avatar asked Dec 06 '22 18:12

Alk


1 Answers

You need to convert your value to dps, you can use the following function to do so:

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

Then, to set the ImageView size to the px value, you can do this:

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

(Change LinearLayout for whatever container your ImageView is in)

Edit: Kotlin Version

The function to convert to Px can be written like this in kotlin (as an extension)

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

Then can use it like this:

view.updateLayoutParams {
    width = 200.toPx(context)
    height = 100.toPx(context)
}
like image 67
Eury Pérez Beltré Avatar answered Dec 09 '22 15:12

Eury Pérez Beltré