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:
{Button buttonX (Button)findViewById(R.id.buttonXName);}
{buttonX.setOnClickListener(new OnClickListener()}
{public void onClick(View v)}
If anyone knows anything, I'd appreciate it.
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.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With