An explanation of the event handling mechanism of Android (ii)-----The event-handling mechanism based on listening

Source: Internet
Author: User
Tags event listener

Monitoring-based event handling mechanism preface:

We develop apps that need to interact with the user----that responds to the user's actions.

This involves the Android event-handling mechanism;

Android gives us two sets of powerful processing mechanisms:

① event handling mechanism based on monitoring

② Callback-based event handling mechanism

In this section, we will first introduce the listener-based event handling mechanism

All right, no more nonsense!  

We need to understand the model of the listening processing mechanism first.

Processing model for listening: working with model diagrams:

Text expression:

Event listener consists of three types of objects, event source, event and event listener .

Processing Flow:

Step 1: set up a listener for an event source (component) to listen for user actions

Step 2: user actions that trigger the listener for the event source

Step 3: generate the corresponding event object

Step 4: Pass the event source object as a parameter to the event listener

Step 5: event listener to judge the event object, execute the corresponding event handler (the corresponding event processing method)

Induction:

Event listener mechanism is a delegated event handling mechanism, event source (component) event handler delegate to event listener

Notifies the event listener when an event source has a development event, and performs the appropriate action

form of Use:

Instance:

This is achieved by clicking on the button and displaying the toast information prompt

To demonstrate, the following are the effects that are implemented in different forms, which can be carefully figured out in code

:

① use anonymous inner classes directly as event listeners

PS: Is our usual most commonly used kind, after Setxxxlistener rewrite the corresponding method inside

It's usually a temporary use, not a high reusability.

Code:

XML is a normal button, which does not give a

Mainactivity.java

 PackageCom.jay.example.innerlisten;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.Toast;Importandroid.app.Activity; Public classMainactivityextendsActivity {PrivateButton btnshow; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Btnshow=(Button) Findviewbyid (r.id.btnshow); Btnshow.setonclicklistener (NewOnclicklistener () {//Override Click event handling method onclick ()@Override Public voidOnClick (View v) {//Show Toast InformationToast.maketext (Getapplicationcontext (), "You clicked the button", Toast.length_short). Show ();    }        }); }    } 
② using an internal class as an event listener

This is not the same as the anonymous inner class above.

Use advantage: can be reused in this class, direct access to all interface components of the external class

Code:

 PackageCom.jay.example.innerlisten;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.Toast;Importandroid.app.Activity; Public classMainactivityextendsActivity {PrivateButton btnshow; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Btnshow=(Button) Findviewbyid (r.id.btnshow); //Direct new an inner class object as a parameterBtnshow.setonclicklistener (NewBtnclicklistener ()); }             //define an inner class, implement the View.onclicklistener interface, and override the OnClick () method    classBtnclicklistenerImplementsView.onclicklistener {@Override Public voidOnClick (View v) {toast.maketext (Getapplicationcontext (),"button is clicked.", Toast.length_short). Show (); }            }}
③ using an external class as an event listener

is to create another Java file that handles the event, which is a rare form of

Because external classes do not have direct access to components in the user interface class, the component is passed into use by constructing methods,

The result is that the code is not concise.

PS: To demonstrate, here by TextView instead of toast display!

Code:

Layout is relatively simple, is a button + text box, here does not give a

Also write an external class:

Myclick.java

 PackageCom.jay.example.innerlisten;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.TextView; Public classMyclickImplementsOnclicklistener {PrivateTextView textshow; //to pass a text box as a parameter     PublicMyclick (TextView txt) {textshow=txt; } @Override Public voidOnClick (View v) {//Text after clicking to set the text box to displayTextshow.settext ("Click on the button!")); }}

Mainactivity.java

 PackageCom.jay.example.innerlisten;ImportAndroid.os.Bundle;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;Importandroid.app.Activity; Public classMainactivityextendsActivity {PrivateButton btnshow; PrivateTextView txtshow; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Btnshow=(Button) Findviewbyid (r.id.btnshow); Txtshow=(TextView) Findviewbyid (r.id.textshow); //direct new to an external class and pass TextView as a parameterBtnshow.setonclicklistener (NewMyclick (txtshow)); }     }
④ directly using activity as an event listener

Just let the activity class implement the ~listener event listener interface and define overriding event handler methods in activity

Eg:activity implements the Onclicklistener interface, overriding the OnClick (view) method

When you add the event listener object for a component, you can directly Setxxxlistener (this)

:

Layout file slightly

Mainactivity.java

 PackageCom.jay.example.innerlisten;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.Toast;Importandroid.app.Activity;//let the activity method implement the Onclicklistener interface Public classMainactivityextendsActivityImplementsonclicklistener{PrivateButton btnshow; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Btnshow=(Button) Findviewbyid (r.id.btnshow); //write this one directlyBtnshow.setonclicklistener ( This); }    //overriding an abstract method in an interface@Override Public voidOnClick (View v) {toast.maketext (Getapplicationcontext (),"Click on the button", Toast.length_short). Show (); }     }

Analysis of important ontouchevent events

The reason why the Ontouchevent event is explained here is not simply that he is an example of an event monitoring mechanism.

And because his invocation process is special, and because this event is something that we use more in our actual development

All view components override this method, which the application can use to handle touch events on the phone screen.

Method declaration:

Public Boolean ontouchevent (Motionevent event);

Use process:

① for a view (component)Setontouchlistener (New Ontouchlistener ())

② overriding the Ontouch () method

③ because there are three kinds of more commonly used touch states:

Motionevent.action_down: Press the

Motionevent.action_move: Mobile

MOTIONEVENT.ACTION_UP: Let go.

So we usually sort by switch,switch (event.getaction), and then each case ~: Handle the corresponding event

Method Invocation Order Resolution:

By method declaration We know that Ontouchevent returns a Boolean value, either True or False

The difference between the two is whether the external method is called after the method in the Ontouch () is called.

Here's a simple example:

We set the Ontouch (), OnClick (), Onlongclick () Three methods for a button, so what is the order of their calls?

A: There are two types of cases:

① returns true: Call Action_down method When pressed, call the Action_move method after the call, as long as the finger keeps pressing the system will constantly respond to this

method, the reason is (Android is sensitive to touch events, although our fingers feel static, but the fingers are constantly trembling vibration); When our fingers leave

The screen, this time call the Motionevent.action_up method, and then the process is done

② returns false: the same process as above, but the other 2 methods are called when you leave the screen:

If you are short-clicking, then the OnClick () method is called

If you are long-pressed, then the Onlongclick () method is called;

And then it's over.

These two situations above are not difficult to understand

Readers can write their own code to verify, and then view the order information of the call through LOG.I ()

Finally, let's show you

Call the use of the Ontouchevent () OnMove method.

The MoveTo () method uses an instance:

This is used more, the example is still old, in the frame layout that section is given out

Here's a brief introduction to the usage:

We just need to get the position of the current click through the parameter event.

x = Event.getx (); Get the x-coordinate of the click

y = event.gety (); Get the y-coordinate of the click

See the code in detail:

MoveTo Method Usage Examples

An explanation of the event handling mechanism of Android (ii)-----The event-handling mechanism based on listening

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.