I would like to introduce a concrete example of the interface used when creating an Android application.
The listener around here is defined in View.java.
With Android Studio, you can jump to the location defined in the class with command + B, so please check it.
It is sometimes called an event listener.
Used when programming with multiple threads.
Reference: Android Developer Processes and Threads
Let's take OnClickListener as an example.
Pass interface as an argument to the setOnClickListener method of the View class.
Button button = new Button(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//What to do when the button is clicked
}
});
You can also assign it to a variable in advance. (I won't do it ...)
Button button2 = new Button(this);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//What to do when the button is clicked
}
};
button2.setOnClickListener(onClickListener);
The new grammar implemented in Java8, Lambda, requires preparation for use on Android.
Refer to this site, -Qiita: Easily write Android apps with lambda expressions!
app/build.gradle
android {
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Add the above two places.
At this time, it is necessary that the version of gradle is 2.1.0 or higher in gradle-wrapper.properties.
Button button3 = new Button(this);
button3.setOnClickListener((View v)->{
//What to do when the button is clicked
});
There seems to be no clear answer to "how should I write it?"
It's a little old article, -How to implement beautiful OnClickListener (Please tell me)
Personally, I like writing in anonymous classes, and I don't really like implementing implements in Acitivyt or Fragment (because it feels weird object-oriented ...)