Set ImageView width and height programmatically?
Asked Answered
H

15

726

How can I set an ImageView's width and height programmatically?

Habitable answered 29/6, 2010 at 21:36 Comment(1)
Footnote for anyone struggling with this coming from another platform. the "size and shape to fit" option is handled beautifully in Android; but it's hard to find. you typically want width match parent, height wrap content, adjustViewBounds turned on, scale fitToCenter and cropToPadding false. then it's automatic. I really hope it helps someone!Botzow
C
1257

It may be too late but for the sake of others who have the same problem, to set the height of the ImageView:

imageView.getLayoutParams().height = 20;

Important. If you're setting the height after the layout has already been 'laid out', make sure you also call:

imageView.requestLayout();
Cabasset answered 10/3, 2011 at 9:45 Comment(11)
If you're setting the height after the layout has already been 'laid out', make sure you call image_view.requestLayout()Girardo
The answer should be edited to include the addendum by @SkripiDefiniens
what if I need wrap_content ?Kerley
@FranciscoCorralesMorales use the static values defined for LayoutParamsWardlaw
@FranciscoCorralesMorales use this for wrap_content image_view.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT .. If the view parent is LinearLayout replace the RelativeLayout with itDelta
do i need to requestLayout first or after layout has been 'laid out'? and is sample height 20 in dips or pixels?Baler
width and height are in pixels.Parrot
So, how to specify the unit? How to say that it's dp, not sp, etc.Saba
@SaeedNeamati, it's px. In order to convert dp to px use methods, for instance, in https://mcmap.net/q/36300/-converting-pixels-to-dp.Fibril
Future readers, use this if creating the view programmatically.Viewing
@SaeedNeamati choose it on your own when pass size. For example: val dp = 30; TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().displayMetrics)Subhuman
R
260

If your image view is dynamic, the answer containing getLayout will fail with null-exception.

In that case the correct way is:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);
Racehorse answered 26/3, 2012 at 17:21 Comment(5)
if I put that code my image disappears. why? ImageView imgLogo = new ImageView(this); imgLogo.setImageDrawable(logo); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(32,32); imgLogo.setLayoutParams(layoutParams); row.addView(imgLogo);Certify
Thanks for this answer, put me on the right track. As an added note, LinearLayout should be set to the parent view type of the image. For example, if your image view is in a gallery, you should use the Gallery layout parameters instead of LinearLayout or you will have casting exceptions.Hosier
@MustafaGüven I had the same problem as you, where my ImageView disappears. The trick is to make the layout part (i.e., <this_part_here>.LayoutParams) be the same as what the parent of the ImageView is. So, for example, if you've placed your ImageView within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams.Inimitable
to elaborate on user($some_number) -> you need to create the LayoutParams according the parent and set them on the child (the imageView) , also requestLayout() doesn't seem to be necessary at time of writingBellew
lol you create new params, bad answer, you just can get the current ones, I mean if you do it (create new ones) then you don't even need xml, then also create/add imageview programmatically...Gretagretal
S
61

This simple way to do your task:

setContentView(R.id.main);    
ImageView iv = (ImageView) findViewById(R.id.left);
int width = 60;
int height = 60;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

and another way if you want to give screen size in height and width then use below code :

setContentView(R.id.main);    
Display display = getWindowManager().getDefaultDisplay();
ImageView iv = (LinearLayout) findViewById(R.id.left);
int width = display.getWidth(); // ((display.getWidth()*20)/100)
int height = display.getHeight();// ((display.getHeight()*30)/100)
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

hope use full to you.

Skeie answered 17/12, 2012 at 13:46 Comment(3)
This is Fine Work for me !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Display display = getWindowManager().getDefaultDisplay(); ImageView iv = (LinearLayout) findViewById(R.id.left); int width = display.getWidth(); // ((display.getWidth()*20)/100) int height = display.getHeight();// ((display.getHeight()*30)/100) LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height); iv.setLayoutParams(parms);Teishateixeira
Why do people declare int variables if they won't be re-used elsewhere? Seems unnecessary but I don't know much about it tbh.Wickiup
just for better understanding @Wickiup ,,, nothing elseSkeie
D
50

I have played this one with pixel and dp.

private int dimensionInPixel = 200;

How to set by pixel:

view.getLayoutParams().height = dimensionInPixel;
view.getLayoutParams().width = dimensionInPixel;
view.requestLayout();

How to set by dp:

int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
view.getLayoutParams().height = dimensionInDp;
view.getLayoutParams().width = dimensionInDp;
view.requestLayout();

Hope this would help you.

Deluge answered 24/5, 2016 at 9:41 Comment(3)
How would I do this for a specific dp value (i.e. not converting from px to dp)?Buffum
@Hiren what is mean by getResources().getDisplayMetrics() when I read the document ,it seem to be DisplayMetrics. Can you please explain me bit briefly. I am new to android ,thanks .Naissant
Caused by: java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object referenceAmalgamate
T
20

If you need to set your width or height to match_parent (as big as its parent) or wrap_content (large enough to fit its own internal content), then ViewGroup.LayoutParams has this two constants:

imageView.setLayoutParams(
    new ViewGroup.LayoutParams(
        // or ViewGroup.LayoutParams.WRAP_CONTENT
        ViewGroup.LayoutParams.MATCH_PARENT,      
        // or ViewGroup.LayoutParams.WRAP_CONTENT,     
        ViewGroup.LayoutParams.MATCH_PARENT ) );

Or you can set them like in Hakem Zaied's answer:

imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
//...
Tremolant answered 25/12, 2015 at 0:40 Comment(0)
V
14

You can set value for all case.

demoImage.getLayoutParams().height = 150;

demoImage.getLayoutParams().width = 150;

demoImage.setScaleType(ImageView.ScaleType.FIT_XY);
Vorster answered 27/7, 2016 at 14:3 Comment(2)
Caused by: java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object referenceAmalgamate
@Amalgamate you need to call this after calling parentView.addView(yourView)Teri
S
13

Simply create a LayoutParams object and assign it to your imageView

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, 150);
imageView.setLayoutParams(params);
Saintly answered 5/1, 2016 at 6:4 Comment(0)
R
11

The best and easiest way to set a button dynamically is

 Button index=new Button(this);
 int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
 int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());

The above height and width are in pixels px. 45 being the height in dp and 42 being the width in dp.

 index.setLayoutParams(new <Parent>.LayoutParams(width, height));

So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams

 index.setLayoutParams(new TableRow.LayoutParams(width, height));
Raised answered 6/12, 2015 at 9:22 Comment(0)
T
6
image_view.getLayoutParams().height 

returns height value in pixels. You need to get the screen dimensions first to set the values properly.

 Display display = context.getWindowManager().getDefaultDisplay();
 DisplayMetrics outMetrics = new DisplayMetrics();
 display.getMetrics(outMetrics);
 int screen_height = outMetrics.heightPixels;
 int screen_width = outMetrics.widthPixels;

After you get the screen dimensions, you can set the imageview width&height using proper margins.

 view.getLayoutParams().height = screen_height - 140;
 view.getLayoutParams().width = screen_width - 130 ;
Treiber answered 1/10, 2015 at 5:59 Comment(0)
V
6

image.setLayoutParams(new ViewGroup.LayoutParams(width, height));

example:

image.setLayoutParams(new ViewGroup.LayoutParams(150, 150));
Verein answered 14/10, 2020 at 6:54 Comment(0)
H
4

In order to set the ImageView and Height Programatically, you can do

            //Makesure you calculate the density pixel and multiply it with the size of width/height
            float dpCalculation = getResources().getDisplayMetrics().density;
            your_imageview.getLayoutParams().width = (int) (150 * dpCalculation);

            //Set ScaleType according to your choice...
            your_imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
Haematoid answered 1/4, 2019 at 9:44 Comment(0)
I
4

kotlin

val density = Resources.getSystem().displayMetrics.density
view.layoutParams.height = 20 * density.toInt()
Iveyivie answered 13/3, 2020 at 6:21 Comment(0)
R
1

In the scenario where the widget size needs to be set programmatically, ensure the below rules.

  1. Set LayoutParam for the Layout in which you are adding that view. In my case I am adding to TableRow so I had to do TableRow.LayoutParams
  2. Follow this code

final float scale = getResources().getDisplayMetrics().density; int dpWidthInPx = (int) (17 * scale); int dpHeightInPx = (int) (17 * scale);

TableRow.LayoutParams deletelayoutParams = new TableRow.LayoutParams(dpWidthInPx, dpHeightInPx); button.setLayoutParams(deletelayoutParams); tableRow.addView(button, 1);

Register answered 21/12, 2018 at 1:9 Comment(0)
M
0

If you want to just fit the image in image view you can use" wrap content" in height and width property with scale-type but if you want to set manually you have to use LayoutParams.

Layoutparams is efficient for setting the layout height and width programmatically.

Motorboating answered 5/3, 2019 at 13:11 Comment(0)
D
0
int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);
Desmid answered 7/5, 2020 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.