UI Events

Once you've added some Views/widgets to the UI, you probably want to know about the user's interaction with them, so you can perform actions. To be informed of UI events, you need to do one of two things:

• Define an event listener and register it with the View. More often than not, this is how you'll listen for events. The View class contains a collection of nested interfaces named On<something>Listener, each with a callback method called On <something> (). For example, View.OnClickListener (for handling "clicks" on a View), View.OnTouchListener (for handling touch screen events in a View), and View.OnKeyListener (for handling device key presses within a View). So if you want your View to be notified when it is "clicked" (such as when a button is selected), implement OnClickListener and define its onClick() callback method (where you perform the action upon click), and register it to the View with setOnClickListener().

• Override an existing callback method for the View. This is what you should do when you've implemented your own View class and want to listen for specific events that occur within it. Example events you can handle include when the screen is touched (onTouchEvent()), when the trackball is moved (onTrackballEventn), or when a key on the device is pressed (onKeyDownn). This allows you to define the default behavior for each event inside your custom View and determine whether the event should be passed on to some other child View. Again, these are callbacks to the View class, so your only chance to define them is when you build a custom component.

Continue reading about handling user interaction with Views in the Handling UI Events document.

0 0

Post a comment