Wednesday, March 19, 2014

Buttons - II

OnClick functionality of buttons can be written in three different ways
  1. By making activity implement OnClickListener and writing onClick method in the activity
  2. By writing an anonymous inner class
  3. Using android:onClick in xml file

Activity implementing OnClickListener

In the first line of your activity, add implements OnClickListener at the end.

    public  class MyActivity extends Activity implements OnClickListener

You will be prompted to import View.OnClickListener. 

When you hover over the classname   you will be prompted to implement onclick method

Select Add unimplemented methods

Editor adds onClick method in the activity. Add the action inside the method.


 @Override  
   public void onClick(View v) {  
     // TODO Auto-generated method stub 
    //Add your code here 
 }  

Now you should link your button to this listener by saying

btn.setOnClickListener(this);

If your class has multiple buttons, they can all use same listener. Then when any of these buttons are pressed, the onClick method is activated. Hence to specify action for your particular button, get the id and check against id of the button.

       public void onCreate(Bundle b){
       ----
       ---
 
           btn = (Button)findViewById(R.id.button1);  
           btn.setOnClickListener(this); 
      }  
      @Override  
      public void onClick(View v) {  
           int id = v.getId();  
           switch(id){  
           case R.id.button1: //your code goes here  
                          
           }  
      }  


 Writing anonymous inner class

In the code add "mybtn.setOnClickListener(new OnClickListener(){---});

 public void onCreate(Bundle b)  
 {  
    ------  
    -------  
    btn = (Button)findViewById(R.id.button1);  
    btn.setOnClickListener(new OnClickListener(){  
         public void onClick(View v){  
           //add your code here 
         }  
   });  

Again editor puts the template of the anonymous class for you :)

Specifying onClick Method in xml file

In the layout file, for the button, add android:onClick value.
  <Button  
     android:id="@+id/button1"  
     style="?android:attr/buttonStyleSmall"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignLeft="@+id/textView1"  
     android:layout_below="@+id/textView1"  
     android:layout_marginTop="29dp"  
     android:onClick="changeText"  
     android:text="Button" />  

Now define the onclick method  in the format public void methodName(View v)

      public void changeText(View v){
  Button b = (Button)v;
  String str = b.getText().toString() ;
  str = str+"clicked    ";
  b.setText(str);
 }


No comments:

Post a Comment