+ - 0:00:00
Notes for current slide
Notes for next slide

Event Handling III - Reacting to Events in Android

Lauren Bricker

CSE 340 Spring 2022

Slide 1 of 40

Today's goals

  • So far we've learned...
    • Model View Controller
    • Events (theory) and Events (in Android) (finish)
  • Today
    • Input dispatch process (finish)
    • Callbacks (theory) and Listeners (in Android)
    • Listeners in Android
  • Maybe Today, Maybe Friday...
    • Other Android Callbacks (Menus)

Administrivia

  • Download Spot the Heron v. 2.0 before tomorrow
  • Accessibility (code and report/reflection) due tomorrow
  • Assignment 4: Menus will be ready this evening (hopefully?)
Slide 2 of 40

Recall: Event Dispatch

Picture of interactor hierarchy connected to an interface and a
dotted line indicating application interface with do_action() replaced
with an actionListener

Callbacks handle application response to events

  • Allows application to update model
  • Can be implemented using toolkit provided listeners
  • Can implment custom listeners for best flexibility
Slide 3 of 40

Recall: Events can represent user actions...

Example: MotionEvent which inherits from InputEvent abstract class.

Slide 4 of 40

Recall: Events can represent abstract concepts...

Android Activity Lifecycle

Android events registered with the system

  • Create: Android is done creating the object
  • Active: in foreground of screen, and receives input
  • Paused: activity lost focus (is no longer displayed on screen)
  • Stopped:
    • Another activity has focus
    • Original activity remains in memory -- perfect place to save data & state
    • Often can be killed by Android OS if not resumed relatively quickly
  • Inactive: after an activity has been killed; or before it is launched
  • Timer: Animation
Slide 5 of 40

Recall: Relating this back to the phone

Application Program
High Level Tools
Toolkit
Window System
OS
Hardware

Application Program:

  • Views
    • (M) Stores local model (am I pressed, etc)
    • (V) Draws itself on screen
    • (C) Implements callbacks for user events (such as onTouch)
  • Whole Application
    • (M) Stores application model (data/state of app)
    • (V) Sets up the interactor hierarchy
    • (C) Implements callbacks for interface events (such as buttonPressed)
Slide 6 of 40

Recall: Relating this back to the phone

Application Program
High Level Tools
Toolkit
Window System
OS
Hardware

Application Program:

  • Views
    • (M) Stores local model (am I pressed, etc)
    • (V) Draws itself on screen
    • (C) Implements callbacks for user events (such as onTouch)
  • Whole Application
    • (M) Stores application model (data/state of app)
    • (V) Sets up the interactor hierarchy
    • (C) Implements callbacks for interface events (such as buttonPressed)
Slide 7 of 40

Android Callbacks

  • onCreate
    • called when the activity is first created
    • we've seen this in our Doodle, Layout, and Spot The Heron apps:
@Override
protected void onCreate(Bundle savedInstanceState) {
// We want to do any view initialization work here
super.onCreate(savedInstanceState);
// Load the XML representation of our layout into the view
setContentView(R.layout.activity_main);
// Any other work we need to do like adding views or
// registering click listeners!
}
Slide 8 of 40

Other Android Callbacks

  • onStart
    • Called when activity is about to be visible to the user
    • Always gets called after onCreate or onRestart
Slide 9 of 40

Other Android Callbacks

  • onStart
    • Called when activity is about to be visible to the user
    • Always gets called after onCreate or onRestart
  • onResume
    • Called when the activity will start interacting with a use
    • Always gets called after onStart
  • ...
Slide 10 of 40

Event Listeners

Putting theory into practice

Slide 11 of 40
  • Implementation strategy

  • Basic goal: notify something of a change

Callbacks in Android

  • At the time Android was created the toolkit developers have no idea how every app may want to respond to events

  • Listeners are an interface that acts as a callback method

Slide 12 of 40

Callbacks in Android

  • At the time Android was created the toolkit developers have no idea how every app may want to respond to events

  • Listeners are an interface that acts as a callback method

    • Recall interfaces specify behavior (but no data) that can be inherited.
Slide 13 of 40

Callbacks in Android

  • At the time Android was created the toolkit developers have no idea how every app may want to respond to events

  • Listeners are an interface that acts as a callback method

    • Recall interfaces specify behavior (but no data) that can be inherited.
  • Must be registered with a particular View
    • The toolkit architecture (implemented in View) then delivers events that arrive at that View to those listeners
    • i.e. once the View is interacted with by the user
Slide 14 of 40

Callbacks in Android

  • At the time Android was created the toolkit developers have no idea how every app may want to respond to events

  • Listeners are an interface that acts as a callback method

    • Recall interfaces specify behavior (but no data) that can be inherited.
  • Must be registered with a particular View
    • The toolkit architecture (implemented in View) then delivers events that arrive at that View to those listeners
    • i.e. once the View is interacted with by the user
  • A View can have listen for different types of interactions
Slide 15 of 40

What is an interface?

Standard Listener Interfaces

The toolkit has pre-defined interfaces so apps or components can respond to events such as clicks or touches.

  • These interfaces are implemented inside View as inner classes
  • More listed in the API Documentation
// User tapped a view
public static interface View.OnClickListener { ... }
// User long pressed on a View
public static interface View.OnLongClickListener { ... }
// State of view has changed
// (e.g. user clicked outside a EditText input box)
public static interface View.OnFocusChangeListener { ... }
// user typed something
public static interface View.OnKeyListener { ... }
Slide 16 of 40

Implementing clicking

Create your button

Register an event listener with the button

Slide 17 of 40

Pressing something!

In general to respond to a click/press/touch

  1. Create your interactor
  2. Register an event listener with the interactor

Examples here

  • Buttons that respond to onClick events
  • Counter Interactor (we created) that responds to onTouch events


Slide 18 of 40

Registering an Event Listener

Three five ways to register an event listener:

  • Creating a separate class/file or an inner class
  • Creating an anonymous inner class
  • Implementing an Interface in your custom view/application
  • Creating an anonymous class as a parameter
  • Lambdas

Examples of all of these in the Counter exercise

Slide 19 of 40

Code for the Counter exercise uses a helper function

/** Method to increment the count field */
private void incrementCount(View v) {
TextView counter = findViewById(R.id.count);
String textCount = counter.getText().toString();
int count = Integer.parseInt(textCount);
counter.setText("" + ++count);
((TextView)findViewById(R.id.whichButton)).setText(((Button)v).getText());
}
Slide 20 of 40

Simplest approach: Implement the method

  • The current class implements the listener interface
  • Override the callback method
// Approach 3 implementation: implement the listener in
// *this* class
@Override
public void onClick(View v) {
incrementCount(v);
}
Slide 21 of 40

Then register the listener

Registration typically done in onCreate()

// Approach 3 implementation: implement the listener in
//*this* class
@Override
public void onClick(View v) {
incrementCount(v);
}
// in onCreate...
// Registering the listener in Approach 3 (using
// this class)
Button b3 = findViewById(R.id.button_three);
if (b3 != null) { // Should always check for null
b3.setOnClickListener(this);
}
Slide 22 of 40

Preferred Approach: Create an Anonymous Inner Class

public class EventExampleActivity extends AppCompatActivity {
// An anonymous inner class as a member variable in an Activity
View.OnClickListener mButtonClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// call the private method in EventExampleActivity
incrementCount(v);
}
};
protected void onCreate(Bundle savedState) {
Button b1 = findViewById(R.id.button_one);
if (b1 != null) {
b1.setOnClickListener(mButtonClickListener);
}
}
}
Slide 23 of 40

incrementCount is a private method Mention that mXxxx variables are private fields and this is a quick way to find all private fields when searching variables in code

Digging deeper: Creating an Anonymous Inner Class

Let's take some time to parse this...

View.OnClickListener mButtonClickListener = new View.OnClickListener() {
  • View.OnClickListener is the variable type (Documentation) - a nested class in View
  • new View.OnClickListener() is the the anonymous object
    • The on method that you MUST implement (in order to create a new object) is OnClick which overrides the abstract method
public void OnClick(View v) { /* stuff in here does the work when a click is received! */ }
Slide 24 of 40

For very simple listeners you can use a lambda

Create the and register the listener all at once with lamba syntax

Button b5 = findViewById(R.id.button_five);
if (b5 != null) { // Should always check for null
b5.setOnClickListener((View v) -> incrementCount(v));
}

To use Lambdas you have to upgrade to Java 8. See these instructions to do this.

Slide 25 of 40

Other Listeners

  • The toolkit has pre-defined interfaces so apps or components can respond to events such as clicks or touches.
  • More listed in the API Documentation
// User tapped a view
public static interface View.OnClickListener { ... }
// User long pressed on a View
public static interface View.OnLongClickListener { ... }
// State of view has changed
// (e.g. user clicked outside a EditText input box)
public static interface View.OnFocusChangeListener { ... }
// user typed something
public static interface View.OnKeyListener { ... }
Slide 26 of 40

Registering Multiple Listeners

Can register more than one listener

For example:

View v = new View();
v.setOnClickListener(...);
v.setOnLongClickListener(...);
Slide 27 of 40

Many Views, Same Listener (1/3)

Event callbacks are passed the View as a parameter

Slide 28 of 40

Many Views, Same Listener (1/3)

Event callbacks are passed the View as a parameter

We can reuse a listener for views that handle the same action (e.g. all 5 buttons could use the same class/method for the action)

Slide 28 of 40

Many Views, Same Listener (2/3)

And we can handle different actions by checking the View or its id:

protected void onCreate(Bundle savedState) {
Button b1 = (Button) findViewById(R.id.button_one);
if (b1 != null) {
b1.setOnClickListener(mButtonClickListener);
}
Button b2 = (Button) findViewById(R.id.button_two);
if (b2 != null) {
b2.setOnClickListener(mButtonClickListener);
}
}
Slide 29 of 40

Many Views, Same Listener (3/3)

You can use the ID of the view to determine where the event originated from

View.OnClickListener mButtonClickListener = new View.OnClickListener({
public void onClick(View v) {
if (v == null) {
return;
}
int viewId = v.getId();
switch (viewId) {
case R.id.button_one: // First Button
Log.d("Button Press", "First Button");
break;
case R.id.button_two: // Second Button
Log.d("Button Press", "Second Button");
break;
default: // Someone else is using the listener!
Log.d("Button Press", "Invalid Button!");
}
}
});
Slide 30 of 40

Marking an event as handled

This ensures only one view gets it (we talk about the algorithm behind this later)

Return boolean value that indicate the event has been handled (true)

/**
* onLongClick - triggered when a view is long clicked
* @param v - the view long pressed
* @return - true if the callback consumed the long click, false otherwise.
**/
boolean onLongClick (View v) { ... };
Slide 31 of 40

Other types of interactors

What other types of interactors have you used in a Graphical User Interface (GUI)?

Slide 32 of 40
  • Menus
  • Drop down list boxes
  • Scroll bars
  • Text Edit boxes
  • Radio buttons/Check boxes

Other types of interactors

What other types of interactors have you used in a Graphical User Interface (GUI)?

  • Menus
  • Drop down list boxes
  • Scroll bars
  • Text Edit boxes
  • Radio buttons/Check boxes
Slide 32 of 40

Menus

Create the menu resource

  • Click on the Resource Manager tab and click on the vertical ...
  • Select Menu
    • If you have a menu already, it will show up in this pane
    • If you don't have a menu already, click the +
    • Name your menu and add your menu items
Slide 33 of 40

Menus

Example: Counter

Full screen window of the menu item resource in a split view with the code and visuals

Slide 34 of 40

Menus

Handle the callback (from the system) with an onCreateOptionsMenu(Menu menu) listener

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
Slide 35 of 40

Menus

But we still need to handle the events generated from the user

public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id != R.id.dropdown_menu) { // if not the parent hamburger menu
if (id == R.id.reset_button_count) {
...
} else if (id == R.id.reset_click_count) {
...
} else {
...
}
return true; // return true if we handled the event!
}
// Otherwise pass it off to the parent class for handling
return super.onOptionsItemSelected(item);
}
Slide 36 of 40

Summary: Relating this back to the phone

Application Program
High Level Tools
Toolkit
Window System
OS
Hardware

Hardware level: electronics to sense circuits closing or movement

  • Difference between hardware (Event vs sampled)
  • Sensor based input

OS: "Interrupts" that tell the Window system something happened

  • Logical device abstraction and types of devices
Slide 37 of 40

Summary: Relating this back to the phone

Application Program
High Level Tools
Toolkit
Window System
OS
Hardware

Windows system: Tells which window received the input

Toolkit Architecture:

  • Receives events from windowing system
  • Packages up Events and determines which Views should get them
  • Calls Callbacks
  • Handles other aspects of MVC (like redraw)
Slide 38 of 40

Summary: Relating this back to the phone

Application Program
High Level Tools
Toolkit
Window System
OS
Hardware

Application Program:

  • Views
    • (M) Stores local model (am I pressed, etc)
    • (V) Draws itself on screen
    • (C) Implements callbacks for user events (such as onTouch)
  • Whole Application
    • (M) Stores application model (data/state of app)
    • (V) Sets up the interactor hierarchy
    • (C) Implements callbacks for interface events (such as buttonPressed)
Slide 39 of 40

End of Deck

Thing to think about...

How would you handle input in a circular component?

Slide 40 of 40

Today's goals

  • So far we've learned...
    • Model View Controller
    • Events (theory) and Events (in Android) (finish)
  • Today
    • Input dispatch process (finish)
    • Callbacks (theory) and Listeners (in Android)
    • Listeners in Android
  • Maybe Today, Maybe Friday...
    • Other Android Callbacks (Menus)

Administrivia

  • Download Spot the Heron v. 2.0 before tomorrow
  • Accessibility (code and report/reflection) due tomorrow
  • Assignment 4: Menus will be ready this evening (hopefully?)
Slide 2 of 40
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
s Start & Stop the presentation timer
t Reset the presentation timer
?, h Toggle this help
Esc Back to slideshow