Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Button setOnClickListener Design

I am building an Android Application. I've noticed that I am creating many repetitions of code similar to this in each of my classes:

Button buttonX = (Button)findViewById(R.id.buttonXName); // Register the onClick listener with the implementation above buttonX.setOnClickListener(new OnClickListener() {     public void onClick(View v)     {         //DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}     }  }); 

I now have fifteen buttons and this is making my code ugly. Does anyone have a class or some examples on how I can turn all these codes into something more efficient, so I can:

  1. Create the button object {Button buttonX (Button)findViewById(R.id.buttonXName);}
  2. Set the listener {buttonX.setOnClickListener(new OnClickListener()}
  3. Determine if it was clicked {public void onClick(View v)}
  4. Then run specific code for each button?

If anyone knows anything, I'd appreciate it.

like image 720
user591162 Avatar asked Apr 07 '11 23:04

user591162


People also ask

What does setOnClickListener do in Android?

OnClickListener and wires the listener to the button using setOnClickListener(View. OnClickListener) . As a result, the system executes the code you write in onClick(View) after the user presses the button. The system executes the code in onClick on the main thread.


1 Answers

If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.

<Button     android:height="wrap_content"    android:width="wrap_content"    android:onClick="myClickHandler" /> 

And in the Java class, use these below lines of code:

class MyActivity extends Activity {     public void myClickHandler(View target) {         // Do stuff     } } 
like image 87
dgmltn Avatar answered Nov 03 '22 18:11

dgmltn