Views also trigger events when a user interacts with a view. For example, when a user clicks on a button, you need to serve the event, and only in this way can you perform some proper behavior. If you want to do this, you need to register for the view views.
Using the example in the previous section, there are two button in the activity. We can use an anonymous class to set the click event for the button.
The public class Uiactivityactivity extends activity {/** called the ' when ' is the ' The activity ' is the ' the '---' @Overri
De public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
---the two buttons are wired to the same event handler---button BTN1 = (button) Findviewbyid (R.ID.BTN1);
Btn1.setonclicklistener (Btnlistener);
Button btn2 = (button) Findviewbyid (R.ID.BTN2);
Btn2.setonclicklistener (Btnlistener); //---Create an anonymous class to act as a button click listener---Private onclicklistener Btnlistener = new Onclicklistener () {public void OnClick (View v) {Toast. Maketext (Getbasecontext (), (Button) v). GetText () + "was clicked", Toast.
Length_long). Show ();}
};
@Override public boolean onKeyDown (int keycode, keyevent event) {switch (keycode) {
Case KeyEvent.KEYCODE_DPAD_CENTER:Toast.makeText (Getbasecontext (),
"Center is clicked", Toast.length_long). Show ();
Break Case KeyEvent.KEYCODE_DPAD_LEFT:Toast.makeText (Getbasecontext (), "left AR
Row is clicked ", Toast.length_long). Show ();
Break Case KeyEvent.KEYCODE_DPAD_RIGHT:Toast.makeText (Getbasecontext (), "right
Arrow is clicked ", Toast.length_long). Show ();
Break Case KeyEvent.KEYCODE_DPAD_UP:Toast.makeText (gEtbasecontext (), "Up Arrow is clicked", Toast.length_long). Show ()
;
Break Case KeyEvent.KEYCODE_DPAD_DOWN:Toast.makeText (Getbasecontext (), "Down AR
Row is clicked ", Toast.length_long). Show ();
Break
return false; }
}
If you click the OK button or Cancel button, the corresponding message appears on the screen, which means that the appropriate event has been set off.
In addition to defining an anonymous class, you can also set an anonymous inner class to handle the event. The following example shows how to handle the EditText Onfocuschange () method.
---Create a anonymous inner class to act as a
onfocus listener---
edittext txt1 = (edittext) Findviewbyid (r.id. TXT1);
Txt1.setonfocuschangelistener (New View.onfocuschangelistener ()
{
@Override public
void Onfocuschange ( View V, Boolean hasfocus) {
toast.maketext (Getbasecontext (), (
edittext) v). GetId () + "has focus-" + hasfocus,< C9/>toast.length_long). Show ();
}
};