Set ImageView width and height programmatically android

Define imageView width heigh dynamically on button click to change image size.

ImageView widget also supports run time image modification events means app developer can modify image height and width programmatically after activity start at application run time. So here is the complete step by step tutorial for Set ImageView width and height programmatically android.

android-project-download-code-button

How to Set ImageView width and height programmatically android.

Upload image inside drawable-hdpi folder.

drawable hdpi folder

Download below sample image and put inside drawable-hdpi folder.

image_new

Code for MainActivity.java file.

 package com.example.imageviewwidthheightprogrammatically_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

 ImageView demoImage;
 Button setSize;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 demoImage = (ImageView)findViewById(R.id.imageView1);
 setSize = (Button)findViewById(R.id.button1);
 
 setSize.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 demoImage.getLayoutParams().height = 150;

 demoImage.getLayoutParams().width = 150;

 demoImage.setScaleType(ImageView.ScaleType.FIT_XY);
 }
 });
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.example.imageviewwidthheightprogrammatically_android_examples.com.MainActivity" >

 <ImageView
 android:id="@+id/imageView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:src="@drawable/image_new" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/imageView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="42dp"
 android:text="Click Here to Set imageview width and height programmatically android" />

</RelativeLayout>

Screenshots:

dynamic settings

Set ImageView width and height programmatically android

Click Here to download Set ImageView width and height programmatically android project.

Leave a Reply

Your email address will not be published. Required fields are marked *