1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Drain Droids

Android Studio For Beginners.Mobile Apps.Android Games.

Thursday, February 7, 2019

How to do Button Click to change Image on Same Screen-Android Studio ImageView



In this short tutorial, what we are going to demonstrate is a click on a button to change the default image to another image on same screen.
This will be achieved using ImageView attribute and Button. The imageView host drawable folder which our images are stored.
Now let start
I added two images in the drawable folder named dog2 and dog3.
The next thing I do is I added ImageView and a button in the mainActivity XML. I adjusted height to 280 just to position the image top as I wanted.
See bellow

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

    <
ImageView
       
android:id="@+id/imageView1"
       
android:layout_width="372dp"
       
android:layout_height="280dp"
       
android:src="@drawable/dog2" />

    <
Button
       
android:id="@+id/btnChangeImage"
       
android:layout_width="match_parent"
       
android:layout_height="46dp"
       
android:text="another image" />

</
LinearLayout >




The next thing I do is writing some code on the java to make the image change on Button click.

First import bellow

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

Then add bellow to Public Class
Button button;
ImageView
image;

Next Add bellow this code on onCreate


addListenerOnButton();

    }

   
public void addListenerOnButton() {

       
image = (ImageView) findViewById(R.id.imageView1);

       
button = (Button) findViewById(R.id.btnChangeImage);
       
button.setOnClickListener(new View.OnClickListener() {

           
@Override
               
public void onClick(View arg0) {
                   
image.setImageResource(R.drawable.dog3);


            }

        });
       
    }
}



Run the app

http://www.draindroids.com/2019/02/learn-android-studio-basicsbeginners.html