PK EventHandling
PK EventHandling
Contents
Events
Widgets and Event Handling
Anonymous Event Listener
Setting Activity as Event Listener
Events
Events
Event: Action that occurs when user interacts with
widgets. An external stimulus your program can
respond to.
e.g. clicks, typing, scrolling, etc.
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)
FIRST METHOD
SECOND METHOD (Preferred Way)
1: Handling Event in a Listener Object
EVENT HANDLING CODE in separate object named myClickListener
Button button;
protected void onCreate(Bundle savedValues) {
...
// STEP 1: Capture our button from layout
button = (Button)findViewById(R.id.corky);
Button button ;