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 :
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" >
android:id="@+id/scroll_view_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#999A9FA1"
android:orientation="horizontal" >
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!!!
解决方案
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);
}