Friday, August 28, 2015

How to set ImageView image from drawable in Android

activity_main.xml

<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:background="#DCDCDC"
    android:padding="24dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set ImageView Image"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_marginTop="16dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java

package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;


public class MainActivity extends Activity {
        private ImageView mImageView;

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

                // Get the context
                MainActivity context = this;

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

                btn.setOnClickListener(v -> {
                        // Set ImageView image from drawable resource
                        mImageView.setImageDrawable(
                                ContextCompat.getDrawable(
                                        context,
                                        R.drawable.flower7
                                )
                        );
                });
        }
}