I am currently trying to get the OnTouchListener for a View via reflection to exchange the Listener with my custom OnTouchListener which I want to use to track touch events. My method works perfectly fine for the OnClickListener, but somehow doesn't work for the OnTouchListener.
My function looks like this:
private fun getOnTouchListener(view: View): View.OnTouchListener? {
var retrievedListener: View.OnTouchListener? = null
try {
val listenerField = Class.forName("android.view.View").getDeclaredField("mListenerInfo")
val listenerInfo: Any?
listenerField.isAccessible = true
listenerInfo = listenerField.get(view)
val touchListenerField = Class.forName("android.view.View\$ListenerInfo").getDeclaredField("mOnTouchListener")
listenerInfo?.let {
retrievedListener = touchListenerField.get(listenerInfo) as View.OnTouchListener
}
} catch (ex: NoSuchFieldException) {
} catch (ex: IllegalAccessException) {
} catch (ex: ClassNotFoundException) {
}
return retrievedListener
}
listenerField.get(view)
returns null. The same approach worked perfectly fine for views with OnClickListeners.
I have seen other answers to similar questions, where this approach worked (Get OnTouchListener object from View by reflection). Yet, it doesn't work for me.
Does someone know how what to do in order to get the listenerInfo?
Aucun commentaire:
Enregistrer un commentaire