PAPB 04A EventHandling
PAPB 04A EventHandling
PAPB 04A EventHandling
event
Note:
One listener is not limited to be attached to one widget. It can
be attached to any widgets for the same events.
Widgets and
Event Handling
Widgets: Views That Have
Events
For a list of the widgets provided by Android, see the
android.widget package.
Some Examples
Button
CheckBox
DatePicker
EditText
ImageView
Spinner (ComboBox)
Or even ViewGroups may also have events
Adding Widget Objects to
Activity
Before widgets and views are manipulatable
through Activity, widgets and views have to be
loaded into Activity using:
View v = findViewById(WIDGET_RESOURCE_ID);
TextView nameView =
(TextView) findViewById(R.id.textViewName);
Event Handling
Widgets (or Views) may have events associated on it
and developer may decide what events are going to be
handled and process.
An event is handled by event listener object.
Event listener object is ANY objects or even anonymous
objects that implements the event listener interface
The listener object therefore can be registered to a
specific widgets to do something for a specified events
http://developer.android.com/guide/topics/ui/ui-events.html
Events listener Interface
Several event listener Interface that handle specific
events are:
View.OnClickListener (for handling "clicks" on a View),
View.OnTouchListener (for handling screen touch events),
View.OnKeyListener (for handling device key presses)
http://developer.android.com/guide/topics/ui/ui-events.html
Event Handling
User Click
Event
Event Handler is a listener object
which handle an event and do
some action based on what it
listen to. View Widget
A listener is any objects that Button
implements the listener interface. onClick()
setOnClickListener()
An Activity could act as an event
listener by implementing the interface
A listener need to be set to a view Event Handler Object
FIRST METHOD
SECOND METHOD (Preferred Way)
1: Handling Event in a Listener Object
EVENT HANDLING CODE in separate object named myClickListener
...
}
2: Let Activity Handle the
Event
Here's the code to handle Button's click event
using the Activity itself
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky); // STEP 1
button.setOnClickListener(this); //STEP 2 – registration
}