Nikolay
Nikolay

Reputation: 354

Get OnTouchListener object from View by reflection

I need modify onTouch action on same View. So I needed in field mOnTouchListener that stored at static class ListenerInfo in public class View I try this:

Field onTouchListenerField = myView.getClass().getDeclaredField("ListenerInfo.mOnTouchListener");

and I get error: No field ListenerInfo.mOnTouchListener in class MyView; (declaration of 'MyView' appears in ...)

Why this code they found fields only in MyView class, not in base View?

Do you have any ideas?

Upvotes: 0

Views: 159

Answers (1)

SMortezaSA
SMortezaSA

Reputation: 589

You can get that field from View.class. but another mistake in your code is you tired to get ListenerInfo.mOnTouchListener field but that's not a field. you should first get mListenerInfo field from View.class and then get mOnTouchListener from that.

Try this, works fine.

View.OnTouchListener mOnTouchListener = null;

try {
    Field mListenerInfoField = View.class.getDeclaredField("mListenerInfo");
    mListenerInfoField.setAccessible(true);
    Object mListenerInfo = mListenerInfoField.get(myView);
    Field mOnTouchListenerField = mListenerInfo.getClass().getDeclaredField("mOnTouchListener");
    mOnTouchListenerField.setAccessible(true);
    mOnTouchListener = (View.OnTouchListener) mOnTouchListenerField.get(mListenerInfo);
    mOnTouchListenerField.setAccessible(false);
    mListenerInfoField.setAccessible(false);
} catch (Exception e) {
    e.printStackTrace();
}

if (mOnTouchListener != null) {
    mOnTouchListener.onTouch(myView, null);
}

Upvotes: 1

Related Questions