Various Listeners that appear in Android application development. There are two major patterns of writing in a java file, and it was confusing, so I will write it as a memorandum.
This sample is an application that displays a message when you press a button.
Event: An operation to be performed on the screen (example: click) Event handler ・ ・ ・ Processing to be performed for the event (Example: Display text when clicked) Listener: Something that detects an event (example: button)
The layout is suitable.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/text" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Listener setting (event detection button installed)
Button button1 = findViewById(R.id.btn);
button1.setOnClickListener(new TestListener());
}
//Creating a listener class(Click the button+Text display)
private class TestListener implements View.OnClickListener {
@Override
public void onClick(View view) {
TextView textView = findViewById(R.id.text);
textView.setText("I clicked button1");
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Describe all together
Button button2 = findViewById(R.id.btn);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView textView = findViewById(R.id.text);
textView.setText("I clicked button2");
}
});
}
}
In Button ・ SetOnClickListener ・ View.OnClickListener ・ OnClick Since the flow is decided, recognize it as one set.
I introduced two, but in View.OnClickListener, it seems to be set in the basic anonymous class. Therefore, pattern 1 should be used as a reference for understanding the structure!
Recommended Posts