Prevent Dropdown Menu

I am using a counter whose adapter is dynamically full.

  • When there are several elements, the spinner behavior is standard. On clicking, a drop-down list is displayed allowing the user to select an item
  • When there is only one item, I want the dropdown menu not to appear and catch the click event to execute the action.

I cannot find a solution to prevent the default behavior (i.e. showing a drop-down list for only one item on click). Any ideas how to do this? Thanks

+5
source share
2 answers

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

Try

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


    }
}
+7

, true onTouch (...), :

    spinner.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return true;
        }
    });
+1

All Articles