How to programmatically set image to ImageView in Android






activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp"
tools:context=".MainActivity"
android:background="#DCDCDC">

<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>





MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;


public class MainActivity extends Activity {
private ImageView mImageView;

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

// Get the widgets reference from XML layout
mImageView = (ImageView) findViewById(R.id.iv);

/*
public void setImageResource (int resId)
Sets a drawable as the content of this ImageView.

Related XML Attributes
android:src

Parameters
resId : the resource identifier of the drawable
*/

// Set the ImageView image programmatically
mImageView.setImageResource(R.drawable.flower5);
}
}