[java] Set ImageView width and height programmatically?

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

This question is related to java android android-emulator android-widget

The answer is


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

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.


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

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.


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


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

Simply create a LayoutParams object and assign it to your imageView

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, 150);
imageView.setLayoutParams(params);

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

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

example:

image.setLayoutParams(new ViewGroup.LayoutParams(150, 150));

You can set value for all case.

demoImage.getLayoutParams().height = 150;

demoImage.getLayoutParams().width = 150;

demoImage.setScaleType(ImageView.ScaleType.FIT_XY);

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

kotlin

val density = Resources.getSystem().displayMetrics.density
view.layoutParams.height = 20 * density.toInt()

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 ;

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-emulator

flutter run: No connected devices How to remove the Flutter debug banner? Android Studio AVD - Emulator: Process finished with exit code 1 Android Studio Emulator and "Process finished with exit code 0" Run react-native on android emulator ERROR Android emulator gets killed Error while waiting for device: Time out after 300seconds waiting for emulator to come online Unfortunately Launcher3 has stopped working error in android studio? updating Google play services in Emulator Android Studio emulator does not come with Play Store for API 23

Examples related to android-widget

How to create custom button in Android using XML Styles How can I do factory reset using adb in android? Setting Action Bar title and subtitle Determine when a ViewPager changes pages Android Image View Pinch Zooming Add padding on view programmatically Changing position of the Dialog on screen android Using setImageDrawable dynamically to set image in an ImageView how to get html content from a webview? Android How to adjust layout in Full Screen Mode when softkeyboard is visible