How to get listener of a view

前端 未结 4 1507
清酒与你
清酒与你 2020-12-28 21:14

I write service that interacts with other apps. It registers listeners on views (buttons, textviews,...), that already have listeners. I need to replace them with my own lis

4条回答
  •  一生所求
    2020-12-28 21:42

    public abstract class ReflectionUtils {
    
        private static final String listenerInfoFieldName = "mListenerInfo";
        private static final String onCLickListenerFieldName = "mOnClickListener";
    
        public static OnClickListener getOnClickListener(View view){
            Object listenerInfo = ReflectionUtils.getValueFromObject(view, listenerInfoFieldName, Object.class);
            return ReflectionUtils.getValueFromObject(listenerInfo, onCLickListenerFieldName, View.OnClickListener.class);
        }
    
        public static  T getValueFromObject(Object object, String fieldName, Class returnClazz){
            return getValueFromObject(object, object.getClass(), fieldName, returnClazz);
        }
    
        private static  T getValueFromObject(Object object, Class declaredFieldClass, String fieldName, Class returnClazz){
            try {
                Field field = declaredFieldClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                Object value = field.get(object);
                return returnClazz.cast(value);
            } catch (NoSuchFieldException e) {
                Class superClass = declaredFieldClass.getSuperclass();
                if(superClass != null){
                    return getValueFromObject(object, superClass, fieldName, returnClazz);
                }
            } catch (IllegalAccessException e) {
            }
            return null;
        }
    
    }
    

    Calling OnClickListener onClickListener = ReflectionUtils.getOnClickListener(myView); on myView will give you the myView's listener that you are looking for.

提交回复
热议问题