Set Imageview Width and Height Programmatically

Set ImageView width and height programmatically?

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

Set Imageview Height And Width Programmatically

You need to create a new LayoutParams object and set the height and width for it and then pass it to the iv.setLayoutParams() method.

TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(100, 80); 
iv.setLayoutParams(layoutParams);

How to change imageview size on button click

you just have to mention the width and the height of the imageView in LayoutParams.

decr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//code to change height and width values of the ImageView

imageView.getLayoutParams().height = 50; //can change the size according to you requirements
imageView.getLayoutParams().width = 50; //--
imageView.requestLayout()
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

}
});

Set ImageView Size Programmatically in DP Java

You need to convert your value to dps, you can use the following function to do so:

public static int dpToPx(int dp, Context context) {
float density = context.getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}

Then, to set the ImageView size to the px value, you can do this:

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)imageView.getLayoutParams();
params.width = dpToPx(45);
params.height = dpToPx(45);
imageView.setLayoutParams(params);

(Change LinearLayout for whatever container your ImageView is in)

Edit: Kotlin Version

The function to convert to Px can be written like this in kotlin (as an extension)

fun Int.toPx(context: Context) = this * context.resources.displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT

Then can use it like this:

view.updateLayoutParams {
width = 200.toPx(context)
height = 100.toPx(context)
}

how to set ImageView width/height automatically

Solution without ConstraintLayout.

class AspectRatioImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): AppCompatImageView(context, attrs, defStyleAttr) {

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
var height = (measuredWidth * 3 ).toInt()

setMeasuredDimension(width, height)
}
}

You can then use width as match_parent and any height while using AspectRatioImageView in XML.



Related Topics



Leave a reply



Submit