Brendan Winter
Brendan Winter

Reputation: 41

Disable buttons based on spinner choice

So I have buttons (not the soft key pad) on the screen but I want some to be disabled (can't click) when you pick a certain spinner option. Like I have the buttons 0-9 (for numeric input) and if "Base 2" (spinner selection 0) is picked I want all the buttons except 0 and 1 to be disabled.

Upvotes: 1

Views: 2405

Answers (2)

dave.c
dave.c

Reputation: 10918

Spinner does not support setOnItemClickListener. If you try and use it, you will get an exception:

java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner

As such, you should use setOnItemSelectedListener:

    spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int position, long id) {
            Toast.makeText(MyActivity.this, "position= "+position+" / id= "+id, Toast.LENGTH_LONG).show();
            switch(position) {
            case 0:
                button0.setClickable(true);
                button1.setClickable(false);
                break;
            case 1:
                button0.setClickable(false);
                button1.setClickable(true);
                break;
            }
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }});

Upvotes: 1

Mats Hofman
Mats Hofman

Reputation: 7240

You can add a OnItemClickListener and react to the option that is given like for example this way

spinner.setOnItemClickListener(new AdapterView.OnItemSelectedListener() 
    {           
        @Override
            public void onItemSelected(AdapterView<?> parent, 
                View view, int position, long id) {

                if(position == 1) 
                    button.setClickable(false);
            }

    });

Upvotes: 1

Related Questions