Skip to content

Commit

Permalink
Rewrite setonclicklistener
Browse files Browse the repository at this point in the history
Reviewed By: dreamolight

Differential Revision: D18880429

fbshipit-source-id: 31982cc310ac51691b9c635213b8bd567fe33555
  • Loading branch information
Christina Xu committed Dec 9, 2019
1 parent f5128e4 commit 373e54a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,44 @@ public static View.OnClickListener getExistingOnClickListener(View view) {
return null;
}

public static void setOnClickListener(View view, View.OnClickListener newListener) {
try {
Field listenerInfoField = null;
Field listenerField = null;
try {
listenerInfoField = Class.forName("android.view.View")
.getDeclaredField("mListenerInfo");
listenerField = Class.forName("android.view.View$ListenerInfo")
.getDeclaredField("mOnClickListener");
} catch (ClassNotFoundException e) { /* no op */
} catch (NoSuchFieldException e) { /* no op */
}

if (listenerInfoField == null || listenerField == null) {
view.setOnClickListener(newListener);
return;
}

listenerInfoField.setAccessible(true);
listenerField.setAccessible(true);

Object listenerObj = null;
try {
listenerInfoField.setAccessible(true);
listenerObj = listenerInfoField.get(view);
} catch (IllegalAccessException e) { /* no op */
}

if (listenerObj == null) {
view.setOnClickListener(newListener);
return;
}

listenerField.set(listenerObj, newListener);
} catch (Exception e) { /* no op */
}
}

@Nullable
@RestrictTo(RestrictTo.Scope.GROUP_ID)
public static View.OnTouchListener getExistingOnTouchListener(View view) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public final class ViewOnClickListener implements View.OnClickListener {
static void attachListener(View hostView, View rootView, String activityName) {
int key = hostView.hashCode();
if (!viewsAttachedListener.contains(key)) {
hostView.setOnClickListener(
ViewHierarchy.setOnClickListener(hostView,
new ViewOnClickListener(hostView, rootView, activityName));
viewsAttachedListener.add(key);
}
Expand Down

0 comments on commit 373e54a

Please sign in to comment.