nilkash
nilkash

Reputation: 7546

How to set Imageview height and width in activity android

Hi I wanted to change height and width property of image view inside my activity I tried it in following way but its not working for me ...

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);

But I am not able to change height and width of imageview src. Is there any mistake I am doing? How to do this? Need help... Thank you...

Upvotes: 0

Views: 12106

Answers (3)

Siddharth Lele
Siddharth Lele

Reputation: 27748

In this piece of code, I am creating a new instance of an ImageView at runtime and setting dimensions to it:

// 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);

This will set the dimensions of the ImageView. They will, however, be in px. Use the code from here if you need dp values: https://stackoverflow.com/a/9563438/450534

UPDATED:

To change the dimensions of an existing ImageView that has already been defined in the XML, use this:

coupon_img.setLayoutParams(new LayoutParams(100, 100));

Upvotes: 4

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21201

I think you are not adding the changed image to the layout..

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

Upvotes: 2

Raj
Raj

Reputation: 1872

try some thing like this...

 LayoutParams params = new LayoutParams(100, 100);
 parantlayout.addView(coupon_img, params);

I think this will help you.

Upvotes: 2

Related Questions