Android custom event listener

Say I want to make my own event listener for my class, how do I do this? Do I need to maintain the stream manually?

+39
android events mobile listener
Nov 28 2018-11-11T00:
source share
3 answers
public class CustomView extends View(){ OnCustomEventListener mListener; : ://some code : : 

Create an interface that will be implemented by your activity:

 public interface OnCustomEventListener { void onEvent(); } public void setCustomEventListener(OnCustomEventListener eventListener) { mListener = eventListener; } 

Now you need to know when the event really happens. For example, when the user touches a point on the screen, override the onTouchEvent method:

 onTouchEvent(MotionEvent ev) { if (ev.getAction==MotionEvent.ACTION_DOWN) { if(mListener!=null) mListener.onEvent(); } } 

Similarly, you can create the specific event that you want. (examples can touch, wait exactly 2 seconds and let go - you will need to do some logic inside the touch event).

In your activity, you can use the customView object to set the eventListener as such:

  customView.setCustomEventListener(new OnCustomEventListener() { public void onEvent() { //do whatever you want to do when the event is performed. } }); 
+106
Nov 28 '11 at 8:20
source share

This can be done as follows.

First create an interface class:

 public interface OnStopTrackEventListener { public void onStopTrack(); } 

Then create a class that controls the interface:

 public class Player { private OnStopTrackEventListener mOnStopTrackEventListener; public void setOnStopTrackEventListener(OnStopTrackEventListener eventListener) { mOnStopTrackEventListener = eventListener; } public void stop() { if(mOnStopTrackEventListener != null) { mOnStopTrackEventListener.onStopTrack(); } } } 

That's all. Let use it now

 Player player = new Player(); player.stop(); //We are stopping music player.setOnStopTrackEventListener(new OnStopTrackEventListener() { @Override public void onStopTrack() { //Code to work when music stops } }); 
+9
Jan 02 '17 at 6:42 on
source share

I found this tutorial VERY USEFUL. It explains the four steps to using a custom listener to manage callbacks in your code:

1. Define an interface as an event contract with methods that define events and arguments that are relevant event data.

2. Set the listener member and installer variable in the child to which the interface implementation can be assigned.

3. The output passes in the listener, which implements the interface and processes events from the child.

4.Trigger events on a specific listener when an object wants to pass events to the owner

Hope it helps!

0
Dec 03 '18 at 10:58
source share



All Articles