An example of the event handling mechanism and finger swipe of the Android platform

Source: Internet
Author: User
Tags event listener

There are two types of event handling mechanisms for the Android platform

Callback-based event handling: Each view in the Android platform has its own callback method for handling events, and developers can implement the required response events by overriding these callback methods in view.

Event processing based on listener interface: The mainstream processing method in object-oriented design, and the way of delegate event processing, the event is delegated to the registered event listener for processing.


1. Callback-based event handling: Rewrite some callback methods specific to Android components

OnKeyDown ()/OnKeyUp (), the method is an abstract method in interface Keyevent.callback, all view implements the interface and re-write the method, which is used to capture the phone keyboard is pressed event. public boolean onKeyDown (int keycode, keyevent event)

Ontouchevent (), the method is defined in the view class, and all of the view subclasses override this method, which the application can use to handle touch events on the phone screen.

Public Booleanontouchevent (Motionevent event)

Onfocuschanged (), can only be overridden in view. This method is a callback method that changes focus, and when a control overrides the method, the method is automatically called when the focus changes to handle the event of focus change. protected void Onfocuschanged (Boolean gainfocus, int direction, Rect previouslyfocusedrect)


2. Event handling based on listener interface: binds a specific event listener to the Android component. The event listener is the interface of the view class . contains a separate callback method. These methods are called by the Android framework when the listener registered in the view is triggered by the user interface action. The following callback methods are included in the event listener interface:

OnClick (): Included in View.onclicklistener. Called when the user touches the item (in touch mode), or is focused on the item with the browse key or the track ball, and then presses the "confirm" key or presses the tracking ball.

Onlongclick (): Included in View.onlongclicklistener. Called when the user touches and controls the item (in touch mode), or is focused on the item with the browse key or the track ball, and then keeps pressing the "confirm" key or pressing the track ball (one second).

Onfocuschange (): Included in View.onfocuschangelistener. Called when the user enters or leaves the item using the Browse key or the track ball.

OnKey (): Included in View.onkeylistener. Called when the user focuses on the item and presses or releases a key on the device.

OnTouch (): Included in View.ontouchlistener. When a user performs an action that is invoked as a touch event, including a press, release, or any mobile gesture on the screen (within the bounds of this item).

Oncreatecontextmenu (): Included in View.oncreatecontextmenulistener. Called when a context menu is being created (as a result of a persistent "long click" Action).


Rules for the delivery and processing of interface events for Android systems

If an interface control sets an event listener, the event is passed to the event listener first

If the interface control does not have an event listener set, interface events are passed directly to the interface control's other event handlers

Interface events can be passed to other event handlers even if the interface control has an event listener set up

Whether to continue passing events to other handler functions is determined by the return value of the event listener handler function.

If the return value of the listener handler is true, indicating that the event has completed processing and that no other handler is required to participate in the process, the event will no longer be passed

If the return value of the listener handler is false, it means that the event has not finished processing, or that an event is required to be captured by another handler, and the events are passed to other event handlers


An example of event processing based on listener interface

On smartphones, many applications need to get the coordinates of the user's finger operation and some user's actions, since the development of Android often uses sliding places, so here is a description of the sliding example:

Package com. touchview;   import android.app.activity;import android.os.bundle;import  android.view.motionevent;import android.view.view;import android.widget.textview;    public class touchviewactivity extends activity {        private TextView eventlable;    private TextView histroy;     private TextView TouchView;        @Override     public void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview (r.layout.main);         touchview =   (TextView)  findviewbyid (R.id.touch_area);         histroy  =  (TextvieW)  findviewbyid (R.id.history_label);         eventlable =   (TextView)  findviewbyid (R.id.event_label);            touchview.setontouchlistener (New view.ontouchlistener ()  {                 @Override              public boolean ontouch (view v, motionevent event)  {                int  action = event.getaction ();                 switch  (Action)  {                 //  when pressed                  case  (Motionevent.action_down):                     display ("Action_down",  event);                      break;                //   When pressed                  case  (MOTIONEVENT.ACTION_UP):                     int historysize = processhistory (Event);                      histroy.settext ("Historical Data"  + historysize);               &Nbsp;     display ("Action_up",  event);                     break;                 //  when Touch                  case  (Motionevent.action_move):                      display ("Action_move",  event);                 }                 return true;             }        });    }        public&nBsp;void display (string eventtype, motionevent event)  {         //  Contact Relative coordinates information         int x =  (int )  event.getx ();        int y =  (int)   Event.gety ();        //  indicates the size of the touch screen pressure          float pressure = event.getpressure ();         //  indicates contact size         float size =  Event.getsize ();        //  get absolute coordinate information          int RawX =  (int)  event.getrawx ();         int RawY =  (int)  event.getrawy ();            string msg =  ";           msg += " Event Type "  + eventType +  "\ n";        msg +=  "relative coordinates " + string.valueof (x)  + ", " + string.valueof (y)  + " \ n ";         msg +=  "Absolute coordinates"  + string.valueof (RAWX)  +  ","  + string.valueof (Rawy)                  +  "\ n";        msg +=  "Contact Pressure"  + string.valueof (pressure)  +  ",";         msg  +=  Contact size  + string.valueof (size)  +  "\ n";         eventlable.settext (msg);     }       public  int processhistory (MotioneVent event)  {        int history =  Event.gethistorysize ();        for  (int i = 0;  i < history; i++)  {             long time = event.gethistoricaleventtime (i);             float pressure = event.gethistoricalpressure (i);             float x =  Event.gethistoricalx (i);             float y  = event.gethistoricaly (i);             Float size = event.gethistoricalsize (i);        }            return history;       }   } 

main.xml Code section:

<?xml version= "1.0"  encoding= "Utf-8"? ><linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android "    android:orientation=" vertical "     android:layout_width= "Fill_parent"     android:layout_height= "Fill_parent" >     <textview        android:id= "@+id/touch_area"         android:layout_width= "Fill_parent"          android:layout_height= "300dip"         android: Background= "#0FF"         android:textcolor= "#FFFFFF"          android:text= "Touch event test Area"         />     <textview        android:id= "@+id/history_ Label "&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;  android:layout_width= "Fill_parent"         android: layout_height= "Wrap_content"         android:text= "Historical data"          />    <TextView         android:id= "@+id/event_label"         android:layout_ Width= "Fill_parent"         android:layout_height= "Wrap_content"          android:text= "Touch event:"          /></linearlayout>


An example of the event handling mechanism and finger swipe of the Android platform

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.