- This is the deprecated method to add this attribute
to a layout or widget:
android:onClick="<nameOfEventHandler>"
- Then add an event handler method to the activity file:
// The id of the layout is defined by this
// line in the linear layout:
android:id="@+id/main"
// Add this line to the linear layout:
android:onClick="changeBackground"
// Add an event handler to the linear layout
// by (1) selecting changeBackground in the
// previous line, (2) enter Alt-Enter, and (3) select
// add click event handler, (4) edit the event
// handler to look like this:
public void changeBackground(View view) {
LinearLayout layout = findViewById(R.id.main);
layout.setBackgroundColor(Color.parseColor("black"));
}
- This is the recommended way to add an event listener to the layout:
// Leave this line in the LinearLayout:
android:id="@+id/main"
// Remove this line from the LinearLayout:
android:onClick="changeBackground"
LinearLayout layout = findViewById(R.id.main);
layout.setOnClickListener( view -> {
layout.setBackground(Color.parseColor("black"));
});
- You may be familiar with anonymous methods in arrow notation from
JavaScript. Whereas JavaScript arrow notation uses the fat arrow:
=>, Java uses the thin arrow: ->.
- Here is the general form of a Java function that uses arrow notation:
param -> {
// Body of the arrow notation function.
}
- Add a click event handler for the textview that changes the text from
"Hello, how are you?"
to
"Good. How are you doing?"
- Add a click event handler for the textview that changes the
text to uppercase.