Friday, July 31, 2015

Example of button click in android

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:
Change image using a single button in AndroidChange image using a single button in Android


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

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:


package com.example.checkblogapp; //your package name

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

Comment to improve this code and share your ideas to make it better...

No comments:

Post a Comment