3.2 Callback-Based Event Handling Mechanism
Category Android Basic Beginner Tutorial
Introduction to This Section
>
In section 3.1, we learned about an event handling mechanism in Android—the listener-based event handling mechanism. Simply put, it involves adding a listener to our event source (component), and when the user triggers an event, the listener handles it, executing different operations based on the event. So, what is the callback-based event handling mechanism? And another question: Do you know what method callback is? I believe many of you understand it but can't explain it clearly. Let's address these questions and analyze the callback event handling mechanism in Android.
1. What is Method Callback?
Textual Explanation:
>
Answer: It is a method to separate functionality definition from functionality implementation, a design idea for decoupling. In Java, callbacks are implemented through interfaces. As a system architecture, it must have its own runtime environment and provide interfaces for users to implement. The implementation depends on the client, allowing for unified interfaces but different implementations. The system calls our implementation class in different states, achieving separation of interfaces and implementations.
Simple Example:
>
For instance: On Friday after school, you ask your mom if the rice is ready, and she says it isn't. Then you tell her: Mom, I'm going to watch Pleasant Goat and Big Big Wolf, call me when the rice is ready! Analysis: You and your mom have agreed on an interface. You use this interface to ask your mom to cook rice. When the rice is ready, your mom uses this interface to inform you, "The rice is ready!"
2. Detailed Explanation of Android Callback Event Handling Mechanism:
In Android, the callback-based event handling mechanism is used in two scenarios:
1) Custom View
>
When a user triggers an event on a GUI component, the component has specific methods to handle the event. Common practice: Extend the basic GUI component and override the event handling methods, i.e., custom view. Note: When using the custom view in the XML layout, you need to use the "fully qualified class name."
Common Callback Methods for View Components:
Android provides some event handling callback methods for GUI components, taking View as an example, including the following methods:
>
① Triggers screen events on the component: boolean onTouchEvent (MotionEvent event); onKeyDown (int keyCode, KeyEvent event); onKeyUp (int keyCode, KeyEvent event); onKeyLongPress (int keyCode, KeyEvent event); onKeyShortcut (int keyCode, KeyEvent event); onTrackballEvent (MotionEvent event); onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect)
Additionally, let's explain what a trackball is, though it's not very useful. You could see it on old BlackBerry phones. When browsing web pages, you can think of the trackball as a mouse. However, this operation can be handled with onTouchEvent, and it's not aesthetically pleasing, so it's rarely used now. If you're interested, you can see it in the original Android emulator by pressing F6!
Code Example: We define a MyButton class extending the Button class and override the onKeyLongPress method. Then, call the custom view in the XML file using the fully qualified class name.
Effect Diagram:
A simple button. Clicking the button triggers the onTouchEvent event. When pressing the keyboard on the emulator, onKeyDown is triggered, and onKeyUp is triggered when leaving the keyboard. We view this through Logcat!
Implementation Code: MyButton.java
public class MyButton extends Button{
private static String TAG = "呵呵";
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
// Override the event triggered by pressing the keyboard
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode,event);
Log.i(TAG, "onKeyDown method is called");
return true;
}
// Override the event triggered by releasing the keyboard
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyUp(keyCode,event);
Log.i(TAG,"onKeyUp method is called");
return true;
}
// Component is touched
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
Log.i(TAG,"onTouchEvent method is called");
return true;
}
}
Layout File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">
<example.jay.com.mybutton.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮"/>
Code Analysis:
>
Since we directly override the three callback methods of Button, after a click event occurs, we don't need to bind the event listener in the Java file to complete the callback. The component handles the corresponding event itself, i.e., the event is handled by the event source (component) itself.
2) Event Propagation Based on Callbacks:
In summary, whether the event propagates outward depends on whether the return value of the method is true or false.
Code Example:
public class MyButton extends Button{
private static String TAG = "呵呵";
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
// Override the event triggered by pressing the keyboard
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode,event);
Log.i(TAG, "Custom button's onKeyDown method is called");
return false;
}
}
main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">
<example.jay.com.mybutton.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Button"
android:id="@+id/btn_my"/>
</LinearLayout>
MainActivity.java:
public class MyActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button btn = (Button)findViewById(R.id.btn_my);
btn.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
Log.i("呵呵","Listener's onKeyDown method is called");
}
return false;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
Log.i("呵呵","Activity's onKeyDown method is called");
return false;
}
}
Screenshot:
Result Analysis: From the above results, we can see that the propagation order is: Listener -> View component's callback method -> Activity's callback method.
Summary
>
This section explained the callback-based event handling mechanism in Android. The key point is the order of event propagation: listener first, then the View component itself, and finally the Activity. The return value of false continues propagation, while true stops it.
-1.0 Android Basic Beginner Tutorial
-1.0.1 2015年最新Android基础入门教程目录 -1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android Apps with Eclipse + ADT + SDK
-1.2.2 Developing Android Apps with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-1.5.1 Git Tutorial: Basic Operations on Local Repositories
-1.5.2 Using GitHub to Set Up a Remote Repository with Git
-1.6 How to Use 9-Patch Images
-1.7 Interface Prototype Design
-1.8 Project Source Analysis (Various Files and Resource Access)
-1.9 Android Application Signing and Packaging
-1.11 Decompiling APK to Retrieve Code and Resources
-2.1 Concepts of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 Detailed Explanation of TextView (Text Field)
-2.3.2 Detailed Explanation of EditText (Input Field)
-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton and Switch
-2.3.7 ProgressBar (Progress Bar)
-2.3.9 RatingBar (Star Rating Bar)
-2.4.1 ScrollView (Scroll Bar)
-2.4.2 Date & Time Components (Part 1)
-2.4.3 Date & Time Components (Part 2)
-2.4.5 Simple Usage of ListView
-2.4.6 Optimization of BaseAdapter
-2.4.7 Focus Issues with ListView
-2.4.8 Solving Checkbox Misalignment in ListView
-2.4.9 Data Update Issues in ListView
-2.5.0 Building a Reusable Custom BaseAdapter
-2.5.1 Implementing Multiple Item Layouts in ListView
-2.5.2 Basic Usage of GridView (Grid View)
-2.5.3 Basic Usage of Spinner (Dropdown List)
-2.5.4 Basic Usage of AutoCompleteTextView (Auto-complete Text Field)
-2.5.5 Basic Usage of ExpandableListView (Expandable List)
-2.5.6 Basic Usage of ViewFlipper (Flip View)
-2.5.8 Detailed Explanation of Notification (Status Bar Notification)
-2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
-2.6.0 Basic Usage of Other Common Dialogs
-2.6.1 Basic Usage of PopupWindow (Floating Box)
-2.6.3 Simple Usage of ViewPager
-2.6.4 Simple Usage of DrawerLayout (Official Side Menu)
-3.1.1 Event Handling Mechanism Based on Listeners
- 3.2 Event Handling Mechanism Based on Callbacks
-3.3 Analysis of Handler Message Passing Mechanism
-3.4 TouchListener vs OnTouchEvent + Multi-touch
-3.5 Listening for Content Changes in EditText
-3.6 Responding to System Setting Changes (Configuration Class)
-3.7 AsyncTask Asynchronous Tasks
-4.1.1 Beginning with Activity
-4.1.2 Intermediate with Activity
-4.2.1 Introduction to Service
-4.2.2 Intermediate with Service
-4.3.1 Beginning with BroadcastReceiver
-4.3.2 Intermediate with BroadcastReceiver
-4.4.1 Introduction to ContentProvider
-4.4.2 Intermediate with ContentProvider – Document Provider
-4.5.2 Passing Complex Data with Intent
-5.1 Basic Overview of Fragment
-5.2.1 Fragment Example: Implementing Bottom Navigation Bar (Method 1)
-5.2.2 Fragment Example: Implementing Bottom Navigation Bar (Method 2)
-5.2.3 Fragment Example: Implementing Bottom Navigation Bar (Method 3)
-5.2.4 Fragment Example: Bottom Navigation Bar + ViewPager for Swiping Pages -5.2.5 Fragment Example Walkthrough — News (Shopping) App List Fragment Simple Implementation
-6.1 Data Storage and Access — File Storage and Read/Write
-6.2 Data Storage and Access — SharedPreferences for Saving User Preferences
-6.3.1 Data Storage and Access — Introduction to SQLite Database
-6.3.2 Data Storage and Access — Further Exploration of SQLite Database
-7.1.1 Android Network Programming Essentials and HTTP Protocol Study
-7.1.2 Android HTTP Request and Response Headers Study
-7.1.3 Android HTTP Request Method: HttpURLConnection
-7.1.4 Android HTTP Request Method: HttpClient
-7.2.1 Android XML Data Parsing
-7.2.2 Android JSON Data Parsing
-7.3.2 Android File Download (1)
-7.3.3 Android File Download (2)
-7.4 Android WebService Invocation
-7.5.1 WebView (Web View) Basic Usage
-7.5.2 WebView and JavaScript Interaction Basics
-7.5.3 Important Considerations for WebView in Android 4.4 and Later
-7.5.6 WebView Handling Webpage Error Code Information
-7.6.1 Socket Network Basics Preparation
-7.6.2 TCP Protocol Based Socket Communication (1)
-7.6.3 TCP Protocol Based Socket Communication (2)
-7.6.4 UDP Protocol Based Socket Communication
-8.1.1 Summary of 13 Drawable Types in Android Part 1
-8.1.2 Summary of 13 Drawable Types in Android Part 2
-8.1.3 Summary of 13 Drawable Types in Android Part 3
-8.2.1 Bitmap (Bitmap) Comprehensive Analysis Part 1
-8.2.2 Bitmap-Induced OOM Issues
-8.3.1 Detailed Explanation of Three Drawing Tool Classes
-8.3.2 Drawing Class Practical Examples
-8.3.3 Paint API — MaskFilter (Mask)
-8.3.4 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 1)
-8.3.5 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 2)
-8.3.6 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 3)
-8.3.7 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 4)
-8.3.8 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 5)
-8.3.9 Paint API — ColorFilter (Color Filter) (1/3)
-8.3.10 Paint API — ColorFilter (Color Filter) (2/3)
-8.3.11 Paint API — ColorFilter (Color Filter) (3/3)
-8.3.12 Paint API — PathEffect (Path Effect)
-8.3.13 Paint API — Shader (Image Rendering)
-8.3.14 Paint Enumeration/Constants and ShadowLayer Shadow Effect
-8.3.15 Paint API — Typeface (Font Style)
-8.3.16 Canvas API Detailed Explanation (Part 1)
-8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection
-8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
-8.4.1 Android Animation Collection — Frame Animation
-8.4.2 Android Animation Collection — Tween Animation
-8.4.3 Android Animation Collection — Property Animation - Introduction
-8.4.4 Android Animation Collection — Property Animation - Further Exploration
-9.1 Using SoundPool to Play Sound Effects (Duang~)
-9.2 MediaPlayer for Audio and Video Playback
-9.3 Using Camera to Take Photos
-9.4 Using MediaRecord for Audio Recording
-10.1 TelephonyManager (Telephony Manager)
-10.2 SmsManager (SMS Manager)
-10.3 AudioManager (Audio Manager)
-10.5 AlarmManager (Alarm Service)
-10.6 PowerManager (Power Service)
-10.7 WindowManager (Window Management Service)
-10.8 LayoutInflater (Layout Service)
-10.9 WallpaperManager (Wallpaper Manager)
-10.10 Sensor Topics (1) — Introduction
-10.11 Sensor Topics (2) — Orientation Sensor
-10.12 Sensor Topics (3) — Accelerometer/Gyroscope Sensor
-10.12 Sensor Topics (4) — Understanding Other Sensors
-10.14 Android GPS Introduction
-11.0 "2015 Latest Android Basic Beginner Tutorial" Completion Celebration~
-12.2 DrySister Meets Girls App (Version 1) — 2. Parsing Backend Data