![](/img/trans.png)
[英]How to set Height Width of ImageView programmatically in android?
[英]How to set Imageview height and width in activity android
嗨,我想在我的活动中更改图像视图的高度和宽度属性,我尝试按照以下方式进行操作,但对我不起作用...
View card_view = getLayoutInflater().inflate(R.layout.card_details1,null);
coupon_img = (ImageView) card_view.findViewById(R.id.coupon_image);
// I tried this ////////
coupon_img.getLayoutParams().height = 20;
coupon_img.getLayoutParams().width = 20;
// I also tried this ////
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
coupon_img.setLayoutParams(layoutParams);
// also this one ////
coupon_img.setMaxHeight(10);
但是我无法更改imageview src的高度和宽度。 我有什么错误吗? 这个怎么做? 需要帮助...谢谢...
在这段代码中,我将在运行时创建一个ImageView
的新实例,并为其设置尺寸:
// SET THE IMAGEVIEW DIMENSIONS
int dimens = 120;
float density = activity.getResources().getDisplayMetrics().density;
int finalDimens = (int)(dimens * density);
LinearLayout.LayoutParams imgvwDimens =
new LinearLayout.LayoutParams(finalDimens, finalDimens);
imgAlbumPhoto.setLayoutParams(imgvwDimens);
// SET SCALETYPE
imgAlbumPhoto.setScaleType(ScaleType.CENTER_CROP);
// SET THE MARGIN
int dimensMargin = 5;
float densityMargin = activity.getResources().getDisplayMetrics().density;
int finalDimensMargin = (int)(dimensMargin * densityMargin);
LinearLayout.LayoutParams imgvwMargin =
new LinearLayout.LayoutParams(finalDimens, finalDimens);
imgvwMargin.setMargins
(finalDimensMargin, finalDimensMargin, finalDimensMargin, finalDimensMargin);
这将设置ImageView
的尺寸。 但是,它们将位于px中 。 如果需要dp值,请使用此处的代码: https : //stackoverflow.com/a/9563438/450534
更新:
要更改已经在XML中定义的现有ImageView
的尺寸,请使用以下命令:
coupon_img.setLayoutParams(new LayoutParams(100, 100));
尝试这样的事情...
LayoutParams params = new LayoutParams(100, 100);
parantlayout.addView(coupon_img, params);
我认为这会对您有所帮助。
我认为您没有将更改的图像添加到布局中。
LinearLayout ll = (LinearLayout)findViewById(R.layout.yourlinearlayout);
image.setLayoutParams(
new LinearLayout.LayoutParams(
bmp.getWidth(),
bmp.getHeight()));
ll.addView(image);// Then add the image to linear layout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.