Follow me android four event-driven model

Video lesson: https://edu.csdn.net/course/play/7621

The Android event-driven model requires deep learning and understanding. The three elements of the event-driven model are as follows:

Event-driven model

Event source : the maker of the event, such as a button

Usually has the function of registering and canceling the listener

Listener : The receiver of the event, usually an object of a class written by yourself

A class that implements the event interface supported by the event source

Event : a specific event generated by the event source

One event source can generate multiple events

A listener can receive multiple events

The event handler is usually located inside the listener

Event-driven model
work steps
 
1. Define the listener and write a processing method for each event 
2. Register the listener object to the event source 
3. When an event occurs, the event source calls the corresponding method in the listener to complete the event processing 


Inner class form : Inner class is to define another class inside one class, and use inner class to define event listener class


class btnListener1 implements View.OnClickListener{ @Override public void onClick(View arg0) {tv1.setText("You pressed to me!"); }}


Listeners usually use Java anonymous classes to implement the definition of anonymous classes and object creation at the same time. The  specific definition format is as follows:  




Use Activity itself as a listener class
Disadvantages: this form may cause confusion in the program structure


public class MainActivity extends Activity implements View.OnClickListener{	……}

Steps to implant events for controls: 1: Determine the source of the event, such as a button. 2: Specify the event to be monitored. In Android, a listener usually handles an event. 


3: Write a listener through an anonymous class and register the listener at the same time

//Find the event source object Button btn = (Button)findViewById(R.id.okbtn);//Register the listener btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Log.d("tip ", "button clicked");}});


Guess you like

Origin blog.51cto.com/2096101/2588823