Search code examples
androidandroid-spinner

Prevent spinner dropdown to show


I am using a spinner whose adapter is dynamically populated.

  • When there are multiple items, the spinner behavior is the standard one. On a click, the dropdown is showed, allowing the user to select an item
  • When there is only one item, I want to prevent the dropdown to appear and catch the click event to perform an action.

I can't find a solution to prevent the default behavior (i.e. showing the dropdown for only one item on a click). Any ideas on how to do this? Thanks


Solution

  • hm... try to use setClickable(fasle) or setEnabled(false) if only one item in spinner.

    Try this

    public class SpinnerActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Spinner spinner = (Spinner) findViewById(R.id.spinner1);
            List<String> list = new ArrayList<String>();
            list.add("list 1");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(dataAdapter);
    
            if (list.size() < 2) {
                spinner.setClickable(false);
                spinner.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            Toast.makeText(SpinnerActivity.this, "Catch it!", Toast.LENGTH_SHORT).show();
                        }
                        return true;
                    }
                });
            }
    
    
        }
    }