Set ImageView Size Programmatically in DP Java

时光怂恿深爱的人放手 提交于 2020-02-06 05:07:12

问题


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:


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)



来源:https://stackoverflow.com/questions/35803313/set-imageview-size-programmatically-in-dp-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!