Skip to content

Instantly share code, notes, and snippets.

@yongkangc
Forked from CodyEngel/AwesomeButtonActivity_2.java
Last active February 3, 2019 11:07
Show Gist options
  • Save yongkangc/5849fb1cfd5cb0c05de08c425140e552 to your computer and use it in GitHub Desktop.
Save yongkangc/5849fb1cfd5cb0c05de08c425140e552 to your computer and use it in GitHub Desktop.
OnClickMethod-Android
public class AwesomeButtonActivity extends AppCompatActivity {
private Button awesomeButton;
private View.OnClickListener awesomeOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
awesomeButtonClicked();
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
awesomeButton = new Button(this);
awesomeButton.setOnClickListener(awesomeOnClickListener);
}
private void awesomeButtonClicked() {
awesomeButton.setText("AWESOME!");
}
}
@yongkangc
Copy link
Author

One reason why I like this option is it is incredibly easy to refactor option one into option two. All you have to do is take your implementation and move it out of setOnClickListener, assign it to a field, and then update your call to setOnClickListener to reference that field.

Another reason why I like this option is it allows you to reuse the implementation. So when one of our customers demands that we add a second button that does the exact same thing as our OG awesome button, all we have to do is call setOnClickListener and pass in the field.

The last reason I wanted to bring up is this creates a seam that will allow us to test this class easier. In the example above we can use Powermock’s Whitebox Class to replace the field with a mock or stub of OnClickListener.

Oh, another positive to this route is it can help you organize your code a bit better as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment