设置ImageView的大小以编程方式DP的Java [英] Set ImageView Size Programmatically in DP Java
本文介绍了设置ImageView的大小以编程方式DP的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要设置的Android
宽度和的ImageView
的高度。在的ImageView
不 XML
存在。它是在这里创建:
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);
}
和它被放置到这个的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没有像素,这样它看起来在所有设备!
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!!!
推荐答案
您需要将您的值转换为DPS,你可以用下面的函数来做到这一点:
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);
}
这篇关于设置ImageView的大小以编程方式DP的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文