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:
- Create the button object
{Button buttonX (Button)findViewById(R.id.buttonXName);} - Set the listener
{buttonX.setOnClickListener(new OnClickListener()} - Determine if it was clicked
{public void onClick(View v)} - Then run specific code for each button?
If anyone knows anything, I’d appreciate it.
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.
And in the Java class, use these below lines of code: