Search code examples
androidspinnersimultaneous-calls

Close Spinners dropdown when two among all in a groupview are clicked simultaneously


I have several drop down (Spinners) in my Android ViewGroup.

When I try to click two of them simultaneously, They both get open. There is however by default behavior in Android that if a spinner is 'opened' and you do a click somewhere, it gets closed: Nothing Selected in the listener gets called on Item Selected Listener.

I want, on simultaneous click over both of the Spinners, none of them should get opened. However on single selection (one Spinner only) it should work correctly.


Solution

  • Say there are two spinners, apply on touch listener on both. or the getView() in the adapter is sufficient (not getDropDownView), but then you would like to handle them in the same space.

    @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            // Toast.makeText(getActivity(), v + " touched",
            // Toast.LENGTH_LONG).show();
    
            try {
                ActionBarActivity context = (ActionBarActivity) getActivity();
                if (context == null) {
                    // Log.d(tag, "OnTouch spinner context: " + context);
                    return false;
                }
                if (main_layout == null) {
                    return false;
                }
                int i = v.getId();
                switch (i) {
                case R.id.spinner1: {
                    Spinner spnTemp = null;
                    spnTemp = (Spinner) main_layout.findViewById(R.id.spinner2);
    
                    if (spnTemp != null) {
                        // spnTemp.setSelected(false);
    //                  Log.d(tag, "OnTouch spinner spnTemp.isPressed(): " + spnTemp.isPressed());
                        if (spnTemp.isPressed()) {
                            spnTemp.setPressed(false);
                        }
                    }
                }
                    break;
                case R.id.spinner2: {
                    Spinner spnTemp = null;
                    spnTemp = (Spinner) main_layout.findViewById(R.id.spinner1);
                    if (spnTemp != null) {
                        // spnTemp.setSelected(false);
    //                  Log.d(tag, "OnTouch spinner spnTemp.isPressed(): " + spnTemp.isPressed());
                        if (spnTemp.isPressed()) {
                            spnTemp.setPressed(false);
                        }
                    }
                }
                    break;
                }
            } catch (Exception e) {
                Log.e(tag, "OnTouch spinner exception");
            }
            return false;
        }