Monday, August 23, 2010

Making Buttons Click!!!

Here is the basic approach:
1. First create a reference to a button in the view xml file (main.xml),
using a <button> tag, e.g., <Button android:id:"@+id/plus" .. />
2. Then use findViewbyId to obtain the id from the xml file (in the id attribute) to the program, e.g.
Button bPlus=(Button)findViewById(R.id.plus)
3. Next set the Button class OnClickListener. If you have set your Activity to implement the OnClickListener interface, then you set it to itself (this). E.g.
bPlus.setOnClickListener(this)
4. To implement the listener, you put a switch to select the id of the button clicked, e.g.
public void onClick(View v){
switch (v.getID()){
   case R.id.plus:
       //do something
      break;
     ...
}

No comments:

Post a Comment