This is fourth android application and this is same as third application but using only one button to change image here, so see third application and compare. Create new project and drag image view, one button view in relative layout and give id iv and bt respectively.

To change image on button click, we are calling a method in Java file but we have to declare this method in XML file, use this code in button tag : android:onClick=”method_name” and use same method name in Java file and pass view object in this method which will keep id of clicked button. The code of android xml file is give below:


<RelativeLayoutxmlns: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>



Now open android Java file and use the same method which is declared in button tag in XML file. Use a Boolean flag to change the image. The code of android Java file is given below:

packagecom.example.checkblogapp; //your package name

importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.ImageView;
importandroid.app.Activity;

publicclassMainActivity extendsActivity {
  Boolean flag=false;
  @Override
  protectedvoidonCreate(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

  publicvoidchange_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;
   }
  }
}

Now runs your project and if you have any doubt please comment. Thanks..  :)


Categories: , , , , , , , , , , , ,

Leave a Reply