Kotlin Android – Set Specific Width for ImageView

To set specific width for ImageView in Kotlin Android, set android:layout_width attribute of ImageView in layout file with required width.

The following code snippet demonstrates to set specific width for ImageView.

<ImageView
	...
	android:layout_width="250dp"
	/>

Example Android Application

Let us create an Android Application with ImageView.

Refer Kotlin Android – ImageView Example to create an Android Application with just an ImageView in LinearLayout, and follow these steps.

Set ImageView Width

Open activity_layout.xml file and switch to design mode.

By default, the layout width of the ImageView is set to wrap the content, which is our ImageView.

ADVERTISEMENT

We can change this value to required width, say 250dp. Click on the wrap_content value for layout_width attribute and set the width to 250dp.

As we can observe in the blueprint, the width of ImageView is changed.

Change ImageView Width in XML Code

If not in Design mode, we can also change the width in Code. Change the value of layout_width for ImageView in activity_main.xml file as shown in the following.

activity_main.xml

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

    <ImageView
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/sample_image" />

</LinearLayout>

Run the Android Application

Now, let us run the Android Application, and see if width of the ImageView is set to the specified value.

Android ImageView - Set Width

Conclusion

In this Kotlin Android Tutorial, we learned how to set specific width for ImageView in Android Application.