Android Custom Event Listener
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 is actually occurring. For example when the user touches a point on screen, override onTouchEvent method:
onTouchEvent(MotionEvent ev) {
if (ev.getAction==MotionEvent.ACTION_DOWN) {
if(mListener!=null)
mListener.onEvent();
}
}
Similarly, you can create a specific event that you want. (examples could be touch down, wait for exactly 2 seconds and release- you would need to do some logic inside touch event).
In your activity, you can use the customView object to set an eventListener as such:
customView.setCustomEventListener(new OnCustomEventListener() {
public void onEvent() {
//do whatever you want to do when the event is performed.
}
});
Custom event listener on Android app
Define a callback interface
public interface NewsUpdateListener
{
void onNewsUpdate(<News data to be passed>);
}Provide a registration facility on the background thread which gets the RSS feed
class <Background processing class name>
{
....
ArrayList<NewsUpdateListener> listeners = new ArrayList<NewsUpdateListener> ();
....
public void setOnNewsUpdateListener (NewsUpdateListener listener)
{
// Store the listener object
this.listeners.add(listener);
}
....
}Fire the callback when news is available
....
for (listener : listeners)
{
listener.onNewsUpdate(<News data to be passed>);
}
....Register listener somewhere during initialization
....
<class <Background processing class object>.registerListener
(
new OnNewsUpdateListener() {
onNewsUpdate(<News Data>) {
// process news data
runOnUIThread(new Runnable() {
public void run() {
// refresh list view
}
}
}
}
....
Java - Create a Custom event and listener
So I made a minimal example maybe that will help you:
You need an interface for your listener:
public interface MyEventListener
{
public void onMyEvent();
}
Then for your String you need some wrapper class that also handles your events
public class EventString
{
private String myString;
private List<MyEventListener> eventListeners;
public EventString(String myString)
{
this.myString = myString;
this.eventListeners = new ArrayList<MyEventListener>();
}
public void addMyEventListener(MyEventListener evtListener)
{
this.eventListeners.add(evtListener);
}
public void setValue(String val)
{
myString = val;
if (val.equals("hello world"))
{
eventListeners.forEach((el) -> el.onMyEvent());
}
}
}
You see that the myString
field is private and only accessible using the setValue
method. This is so we can see when our event condition triggers.
And then you only need some implementation of this, such as:
EventString temp = new EventString("test");
temp.addMyEventListener(() -> {
System.out.println("hello world detected");
});
temp.setValue("hello world");
Android custom view event listeners not working properly without static reference
In your implementation there are two instances of your custom compound view comes into play, one is in the layout (activity layout) and other one is explicitly created one in the activity onCreate
method.
barcodeScannerView = new BarcodeScannerView(this);
barcodeScannerView.setOnScannerListener(this);
You have set the listener to the explicitly created one which doesn't have clue about view used in the layout, simply they are two instances. You should use the instance created (inflated) in the xml as follows.
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
barcodeScannerView = (BarcodeScannerView) findViewById(R.id.barcode_scanner);
barcodeScannerView.setOnScannerListener(this);
}
barcode_scanner
should be the id you have given to the compound view used in the activity layout.
How do I set a Java library's custom event listener in Kotlin?
You can just paste the code in Android Studio and it will suggest to you to convert it to Kotlin code
The same code in Kotlin will be like this
val menu = findViewById<CircleMenuView>(R.id.circle_menu)
menu.setEventListener(object : CircleMenuView.EventListener {
override fun onMenuOpenAnimationStart(view : CircleMenuView) {
Log.d("D", "onMenuOpenAnimationStart");
}
})
How to define custom events and event listeners in Android?
Use Broadcast
Intents to notify listeners of system or application/custom events..
send a Broadcast
using sendBroadcast
method whenever your custom event occurs..
Intent intent = new Intent(NEW_Intent);
intent.putExtra(“Test”,Test1);
sendBroadcast(intent);
To create a new Broadcast Receiver(which will listen to your event/broadcast), extend the BroadcastReceiver
class and override the onReceive
event handler.The onReceive
method will be executed when a Broadcast
Intent is received that matches the Intent Filter used to register the receiver.
Register your receiver in either Manifest file or in the code..
//in xml
<receiver android:name=”.ReceiverName”>
<intent-filter>
<action android:name=”com.paad.action.NEW_INTENT”/>
</intent-filter>
</receiver>
//in code..
IntentFilter filter = new IntentFilter(NEW_INTENT);
ReceiverName r = new ReceiverName();
registerReceiver(r, filter);
using custom event listener java
MainActivity.locationListeners
is an instance member and cannot be accessed statically like you are currently trying to do in WeatherDbAccess
.
What you should do instead since WeatherDBAccess
is a singleton is register and unregister it as a locationListener
from within MainActivity
. It should be in the same life cycle callback methods you are registering and unregistering the LocationListener
.
Since you aren't showing that code lets assume it is in onResume()
and onPause()
but you can put the add and remove methods wherever they really belong.
@Override
public void onResume() {
super.onResume();
locationListeners.add(WeatherDBAccess.Instance());
}
@Override
public void onPause() {
super.onPause();
locationListeners.remove(WeatherDBAccess.Instance());
}
Related Topics
Send Post Request with Params Using Retrofit
Android How to Runonuithread in Other Class
Parse JSON Array Response Using Retrofit & Gson
How to Launch Front Camera with Intent
Adb Got Two Same Serial Numbers When Connected to Two Smart Phones
Naming My Application in Android
How to Unregister Broadcastreceiver
Validation Allow Only Number and Characters in Edit Text in Android
Rotate an Yuv Byte Array on Android
Surfacetexture's Onframeavailable() Method Always Called Too Late
Kotlin Error:Could Not Find Org.Jetbrains.Kotlin:Kotlin-Stdlib-Jre7:1.0.7
Android: Notifydatasetchanged(); Not Working
Whatsapp Message Layout - How to Get Time-View in the Same Row
Session 'App' Error While Installing APK