get On Click Listener for a View via reflection - Android User Interface

Android examples for User Interface:View Click

Description

get On Click Listener for a View via reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

import android.view.View;
import android.view.View.OnClickListener;

public class Main {
    public static OnClickListener getOnClickListener(View view) {
        OnClickListener listener = null;
        try {//from  ww  w. ja  va 2 s .  co  m
            Field listenerInfoField = null;
            listenerInfoField = View.class
                    .getDeclaredField("mListenerInfo");
            if (listenerInfoField != null) {
                listenerInfoField.setAccessible(true);
            }
            Object myLiObject = null;
            myLiObject = listenerInfoField.get(view);

            // get the field mOnClickListener
            Field listenerField = null;
            listenerField = Class.forName("android.view.View$ListenerInfo")
                    .getDeclaredField("mOnClickListener");
            if (listenerField != null && myLiObject != null) {
                listener = (View.OnClickListener) listenerField
                        .get(myLiObject);
            }
        } catch (Exception ex) {
            listener = null;
        }
        return listener;
    }
}

Related Tutorials