[Android] Interface example

I would like to introduce a concrete example of the interface used when creating an Android application.

interface example

Various listeners

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.

thread

Used when programming with multiple threads.

Reference: Android Developer Processes and Threads

Example of writing

Let's take OnClickListener as an example.

Pass an anonymous class as an argument

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);

Use lambda expression

Preparation

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.

Write in lambda expression

Button button3 = new Button(this);
button3.setOnClickListener((View v)->{
    //What to do when the button is clicked
});

Finally

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

Recommended Posts

[Android] Interface example
Interface usage example
interface
Android view
Interface benefits
java (interface)
new interface
[java] interface
Example title