[英]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.