From that I\'ve read you can assign a onClick
handler to a button in two ways.
Using the android:onClick
XML attribute where you just use t
With Java 8, you could probably use Method Reference to achieve what you want.
Assume this is your onClick
event handler for a button.
private void onMyButtonClicked(View v) {
if (v.getId() == R.id.myButton) {
// Do something when myButton was clicked
}
}
Then, you pass onMyButtonClicked
instance method reference in a setOnClickListener()
call like this.
Button myButton = (Button) findViewById(R.id.myButton);
myButton.setOnClickListener(this::onMyButtonClicked);
This will allow you to avoid explicitly defining an anonymous class by yourself. I must however emphasize that Java 8's Method Reference is actually just a syntactic sugar. It actually create an instance of the anonymous class for you (just like lambda expression did) hence similar caution as lambda-expression-style event handler was applied when you come to the unregistering of your event handler. This article explains it really nice.
PS. For those who curious about how can I really use Java 8 language feature in Android, it is a courtesy of retrolambda library.