Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 934
Breiz Avatar asked Aug 21 '12 20:08

Breiz


2 Answers

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;
                }
            });
        }


    }
}
like image 157
Georgy Gobozov Avatar answered Nov 11 '22 12:11

Georgy Gobozov


To prevent spinner from showing drop-down list, I only return true in onTouch(...), like this:

    spinner.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return true;
        }
    });
like image 28
sweet-2 Avatar answered Nov 11 '22 11:11

sweet-2