Home » Android » Remove a listener from a view in android

Remove a listener from a view in android

Posted by: admin April 23, 2020 Leave a comment

Questions:

Is there any way to remove a Listener from a View in android? I have a Checkbox that I attached a CheckChangedListener to. The problem is that calling setChecked() on it causes my listener to fire.

If I can’t just remove a listener, is there a way to prevent the listener from firing when I call setChecked() manually versus it being checked from a touch event?

How to&Answers:

Well, I found the answer. This doesnt appear to be documented anywhere, but I went through the code for the View class and if you pass null to the setClickListener methods, it will remove the listener.

checkbox.setOnCheckChangedListener(null);

This should work for any event listener.

Answer:

Why have you got a checkChangeListener? If you’d use an onClicklListener it might just work for you?

Answer:

You could try setting the listener to one that does nothing before calling setChecked() and then putting the useful one back afterwards.

Answer:

I’ve had similar issues with the Spinner view. My solution was to create a class member variable that I check in the OnItemSelected method. Before I change the contents/selection of the Spinner programmatically I set this variable to true. When OnItemSelected fires, if the variable is true I change it to false and just return without doing any work. The downside to this is that it makes troubleshooting difficult since this variable gets set all throughout my code.

Answer:

You just use removeListener(this). Am I missing something here?