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.
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
}
}