Created
May 15, 2013 06:48
-
-
Save seadowg/5582067 to your computer and use it in GitHub Desktop.
Cleaner (IMO) Event Handling in Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Standard way of hooking up Events: | |
public class EventActivity extends Activity { | |
public onCreate(Bundle savedInstanceState) { | |
findViewById(R.id.button_one).setOnClickListener(new View.OnClickListener) { | |
@Override | |
public void onClick(View view) { | |
Toast toast = Toast.makeText(EventActivity.this, "Clicked One!", Toast.LENGTH_SHORT); | |
toast.show() | |
} | |
} | |
findViewById(R.id.button_two).setOnClickListener(new View.OnClickListener) { | |
@Override | |
public void onClick(View view) { | |
Toast toast = Toast.makeText(EventActivity.this, "Clicked Two!", Toast.LENGTH_SHORT); | |
toast.show() | |
} | |
} | |
} | |
} | |
// Nicer way: | |
public class EventActivity extends Activity implements View.OnClickListener { | |
public onCreate(Bundle savedInstanceState) { | |
findViewById(R.id.button_one).setOnClickListener(this); | |
findViewById(R.id.button_two).setOnClickListener(this); | |
} | |
public void onClick(View view) { | |
if (view.getId() == R.id.button_one) { | |
Toast toast = Toast.makeText(this, "Clicked One!", Toast.LENGTH_SHORT); | |
toast.show(); | |
} else if (view.getId() == R.id.button_two) { | |
Toast toast = Toast.makeText(this, "Clicked One!", Toast.LENGTH_SHORT); | |
toast.show(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment