How to set ImageView width and height programmatically

In this android programming code example, we are going to illustrate how to set ImageView width and height programmatically.

The easiest way to set the width and height of an ImageView is in XML layout file.

But there are situation where we might need to change the width and height of already created ImageView or to dynamically create a new ImageView, then the solution below can become handy.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name"
        android:src="@drawable/camera" />

</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView = findViewById(R.id.imageView2);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }
}

As can be seen in the code above, the width and height of the ImageView is set to MATCH_PARENT.

imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

android_imageView_width_height

Instead of using MATCH_PARENT, you can also use WRAP_CONTENT

imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

Finally, if you want to specify a numeric number as the value of the width and height then you can achieve it as shown below.

imageView.setLayoutParams(new LinearLayout.LayoutParams(200, 200));

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment