how to change image when click on button in android

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#b43" >
<ImageView
   android:id="@+id/iv"
   android:layout_width="200dp"
   android:layout_height="200dp"
   android:layout_alignParentTop="true"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="72dp"
/>
<Button
   android:id="@+id/bt"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_below="@+id/iv"
   android:layout_centerHorizontal="true"
   android:onClick="change_image"
   android:textSize="20sp"
   android:text="Change image" />
</RelativeLayout>


MainActivity.java

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

public class MainActivity extends Activity {
  Boolean flag=false;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

  //mess method is declared in XML file
  //This function will call when we click on button
  //and we have to pass View object in this method
  //which will take id of clicked button

  public void change_image(View v)
  {
    ImageView iv=(ImageView)findViewById(R.id.iv);
    //use flag to change image
    if(flag==false)
  {
      iv.setImageResource(R.drawable.myimage);
      flag=true;
    }
    else
    {
      iv.setImageResource(R.drawable.myimage2);
      flag=false;
    }
  }
}

Comments

Popular posts from this blog

how to fetch blob image gallery in php html sql

how to save image to pdf in android

How to create album view with fancybox slider view in html php complete code