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
Make two instances of OnCLickListener and assign first or second to button:
Button b = (Button) findViewById(R.id.Button1);
OnClickListener listener_new = new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("APP", "NEW CLICK LISTENER ACTIVE");
}
};
OnClickListener listener_old = new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("APP", "OLD CLICK LISTENER ACTIVE");
}
};
//setting listener
b.setOnClickListener(listener_old);
b.callOnClick();
//changing listener
b.setOnClickListener(listener_new);
b.callOnClick();
//return your old listener!
b.setOnClickListener(listener_old);
b.callOnClick();
ADDED:
OnClickListener is protected field of Button class, inherited from View class. Name of the field "mOnClickListener". I can't get it even through reflection.
void getListener(Button b) {
java.lang.reflect.Field field = getClass().getSuperclass().getSuperclass().getDeclaredField("mOnClickListener");
}
So You can't get existing listener of the Button if You don't have access to code where it created.
But if You have access to objects of Activity (and we know You have because setting new listener to button), You could add your button with your listener on that activity. Make existing button invisible. And than rollback when necessary.