Android 里面自定义监听器我没搞明白. 监听器是能够做到每时每刻监听是吗? 那像这些自己写出来的监听器究竟是怎么做到监听的?
像这个Android 帮助文档上的实现 dialog 的代码(代码如下), 自己编的一个 interface 被 MainActivity 继承为什么就能做到监听? — NoticeDialogListener
为什么能够接收到点击按钮的事件呢?
以下是上述文档的代码. 当然我问的也不仅仅是这个代码了… 谢谢回答!
For example, here's a DialogFragment that defines an interface through
which it delivers the events back to the host activity:public class NoticeDialogFragment extends DialogFragment { /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface NoticeDialogListener { public void onDialogPositiveClick(DialogFragment dialog); public void onDialogNegativeClick(DialogFragment dialog); } // Use this instance of the interface to deliver action events NoticeDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the NoticeDialogListener so we can send events to the host mListener = (NoticeDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement NoticeDialogListener"); } } ... }
The activity hosting the dialog creates an instance of the dialog with
the dialog fragment's constructor and receives the dialog's events
through an implementation of the NoticeDialogListener interface:public class MainActivity extends FragmentActivity implements NoticeDialogFragment.NoticeDialogListener{ ... public void showNoticeDialog() { // Create an instance of the dialog fragment and show it DialogFragment dialog = new NoticeDialogFragment(); dialog.show(getSupportFragmentManager(), "NoticeDialogFragment"); } // The dialog fragment receives a reference to this Activity through the // Fragment.onAttach() callback, which it uses to call the following methods // defined by the NoticeDialogFragment.NoticeDialogListener interface @Override public void onDialogPositiveClick(DialogFragment dialog) { // User touched the dialog's positive button ... } @Override public void onDialogNegativeClick(DialogFragment dialog) { // User touched the dialog's negative button ... } }
Because the host activity implements the NoticeDialogListener—which is enforced by the onAttach() callback
method shown above—the dialog fragment can use the interface callback
methods to deliver click events to the activity:public class NoticeDialogFragment extends DialogFragment { ... @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.dialog_fire_missiles) .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Send the positive button event back to the host activity mListener.onDialogPositiveClick(NoticeDialogFragment.this); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Send the negative button event back to the host activity mListener.onDialogNegativeClick(NoticeDialogFragment.this); } }); return builder.create(); } }
This is essentially a method call. Suppose we have two classes A and B, and we expect to call a method of B at a certain moment in A. We can let A keep a reference to B and make method calls at the appropriate time:
The above code is implemented. At a certain moment in A (when something happens), we notify B to do something. This is a simple listening mode. You see, here is not B monitoring A's actions all the time, but A actively triggering B's method at a certain moment.
Here, replace B with Listener and it becomes the familiar listener.
So we can write a subclass of B and implement a custom listener:
In terms of design patterns, there is a recommended approach called "use more combination and less inheritance", which means that you should use more interfaces and less inheritance. Let's change B above to interface:
Then replace the previously inherited implementation with the interface implementation:
You can see that the usage is exactly the same as before.
Replace interface B with interface OnClickListener. Is it much clearer? This is called
观察者模式
in design pattern.Recommend a book: "Head First Design Pattern", the first two chapters of which introduce
Strategy Pattern
and策略模式
和观察者模式
, which is what I mentioned above.Don’t understand the listener literally. It does not actively check whether the time occurs, so there is no such thing as every moment.
For us, Listener in Android is actually just a kind of Callback, a callback method. It is a method called by the event initiator or internal handler when an event occurs.
The Listener class written by myself is not to be able to listen to events because it inherits from so and so, but to find a way to tell the initiator or internal handler of the event that when an event occurs, the specified method in this Listener needs to be called. This is usually The setListener process to be done.
This logic has been deduced very clearly in the code you gave. Please look at the code carefully first.
This is a design pattern, but the name is listener. It is not actively triggered, but passive. Once you understand this pattern, you can write some yourself. This is what we usually call callbacks.
Java's Listener is an interface that specifies callback functions. The implementation class of Listener (usually an anonymous inner class) is the callback function object itself. If you want to pass a function object (also called a closure) in Java, you need to do this.
A long time ago, when I was learning Java, I also asked my classmates this question. The person you adopted made it very clear that this is essentially a method call.
In fact, as long as you listen carefully in class and type the code typed by the teacher carefully after class, you will understand the problem.
What is certain is that you always like to put off the problem and figure it out later. This is not okay. of.
It is recommended to type more code, no less than 700 lines per day.
You think there is no code to type? When asking questions that others have figured out, you must type the code three times. If you don’t type the code, type some meaningful small programs.
Persisting in coding means staying strong from the beginning.