modabeckham
modabeckham

Reputation: 247

Clear the selected value from android spinner

Once the check box is check then the spinner will be show and once the check box is unchecked then the spinner will be hidden. I have shown that combination in the below image.

enter image description here

I have achieved this using below code I have shown.

halfHalfCB.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                if (halfHalfCB.isChecked()) {
                    extraDescriptionHalfSP.setVisibility(View.VISIBLE);
                    textview.setVisibility(View.VISIBLE);
                } else {
                    extraDescriptionHalfSP.setVisibility(View.GONE);
                    textview.setVisibility(View.GONE);
//                  String extraDescriptionHalf = extraDescriptionHalfSP
//                          .getSelectedItem() != null ? extraDescriptionHalfSP
//                          .getSelectedItem().toString() : null;
//                          extraDescriptionHalf = null;
                }
            }

        });

        addToCartButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                try {
                    String extraDescriptionHalf = extraDescriptionHalfSP
                            .getSelectedItem() != null ? extraDescriptionHalfSP
                            .getSelectedItem().toString() : null;

Actually my problem is once the check box is checked and then user select a value from spinner and then user unchecked the check box. I want to clear the selected value from the spinner (or make the selected value null). How can I do that? From my current code spinner carries the selected item.

Any help will be highly appreciated.

Upvotes: 4

Views: 9751

Answers (3)

Fahim
Fahim

Reputation: 12378

Use this

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

            if(isChecked){
                spinner.setVisibility(View.VISIBLE);
            }else{
                spinner.setVisibility(View.GONE);
            }
        }
    }); 

Upvotes: 0

vinitius
vinitius

Reputation: 3274

I think you could do it like this:

  ...
  else {
                extraDescriptionHalfSP.setVisibility(View.GONE);
                extraDescriptionHalfSP.setSelection(-1);
                textview.setVisibility(View.GONE);
  ...

Upvotes: 2

Tharif
Tharif

Reputation: 13971

To remove items from the spinner you can use :

myspinner.setAdapter(null);

Upvotes: 3

Related Questions