Catching an event when spinner drop down is dismissed

Kanth picture Kanth · Nov 7, 2013 · Viewed 9.1k times · Source

I want to catch an event when spinner drop down is dismissed. We can catch it when the user clicks on any item in the onItemSelected(). But I want to catch even when user touches outside of the drop down area or back button as these too make it disappear. In these two causes when I observed log, it says "Attempted to finish an input event, but the input event receiver has already been disposed"

I observed the source code, this is printed from the InputEventReceiver.java in the finishInputEvent(InputEvent event, boolean handled) method. But it's a final method, so there is no point of overriding it. Can some one please suggest the way to handle when the drop down is dismissed in those cases?

Answer

alphonzo79 picture alphonzo79 · Nov 16, 2013

What about looking for another event like onDetachFromWindow? A spinner doesn't have any of the regular lifecycle events that we work with a lot -- it would be nice to have an onStop or onDestroy to work with. Of course, you would have to extend the spinner class and create an interface to define your own listener:

public class ChattySpinner extends Spinner {
    private ChattySpinnerListener chattyListener;

    public ChattySpinner(Context context) {
        super(context);
    }

    public ChattySpinner(Context context, int mode) {
        super(context, mode);
    }

    public ChattySpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ChattySpinner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ChattySpinner(Context context, AttributeSet attrs, int defStyle, int mode) {
        super(context, attrs, defStyle, mode);
    }

    public void setChattyListener(ChattySpinnerListener listener) {
        this.chattyListener = listener;
    }

    @Override
    protected void onDetachedFromWindow() {
        if(chattyListener != null) {
            chattyListener.onDetach();
        }

        super.onDetachedFromWindow();
    }

    public interface ChattySpinnerListener {
        public void onDetach();
    }
}

And in your layout XML you want to make sure you specify this control instead of your normal spinner, and in your code set the listener with the implementation of whatever you want to have done when the spinner detaches. It will be up to you to figure out on the client side how to track whether something has been selected or not, maybe by setting a variable in the onItemSelected method that you give the selection listener.