Closing dropdown in Spinner in Android

2019-06-08 04:39发布

问题:

I need to animate an icon of an arrow when opening and closing a spinner in Android. I can rotate the arrow when opening the spinner: I just put a setOnTouchListener on the Spinner.

The problem comes, when the dropdown is closed, or hidden, because I don't know how to set a listener or something like that on that action.

Anybody has an idea about how to do this, if possible?

Thanks a lot in advance.

回答1:

I do not know why Google can not do it for so long, but you can solve the problem this way:

You must override the protected method "onDetachedFromWindow" for Spinner, make it as public method, and calling forth it by clicking on the item in your CustomSpinnerAdapter.

For example:

    public class CustomSpinner extends Spinner
    {
        Context context = null;

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

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

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

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

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

        @Override public void onDetachedFromWindow()
        {
            super.onDetachedFromWindow();
        }
    }

I hope you know how to create SpinnerCustomAdapter and insert this CustomSpinner in xml.



回答2:

You can do something like this,

 boolean bflag=true;//declare it as public

     spinner.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub

                 if(bflag==true)
                {
                    //first animation code goes here
                    Toast.makeText(getActivity(), "on", Toast.LENGTH_SHORT).show();
                    bflag=false;
                }

                else
                {
                    //second animation code goes here
                    Toast.makeText(getActivity(), "off", Toast.LENGTH_SHORT).show();
                    bflag=true;
                }


                return false;
            }

        });


回答3:

try this way

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // // called when spiner will closed

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // called when spiner will closed

            }
        });