Spinner delete items

后端 未结 4 1984
南笙
南笙 2021-01-18 10:29

I have developed an application in which i have one edit text value of edit text is entered in spinner on button clicked an the item i select to delete gets deleted but the

相关标签:
4条回答
  • 2021-01-18 11:08

    For me the accepted answer throwed an exception so what I did was this.

        ArrayAdapter adapter = new ArrayAdapter<>(getActivity(),
    android.R.layout.simple_spinner_item, Collections.emptyList());
    spinner.setAdapter(adapter);
    
    0 讨论(0)
  • 2021-01-18 11:10

    I had the same problem. Doing this did solve the problem, by emptying the spinner:

    mySpinner.setSelection(Adapter.NO_SELECTION);
    
    0 讨论(0)
  • 2021-01-18 11:15

    for delete all items use:

    mySpinner.setAdapter(null);
    

    if you want to delete a particular item, remove this from m_adapterForSpinner and then:

    mySpinner.setAdapter(m_adapterForSpinner);
    
    0 讨论(0)
  • 2021-01-18 11:27

    Remember: methods "remove" and "clear" do not work with ArrayAdapter for Android 2.3.3 and lower. You'll receive error message "Unsupported operation.... bla bla bla". May be they work with Android 4.0 and up, I don't know. Here is my solution which works even with minSdkVersion="5".

    1. Create Spinner and fill it with test data This code is in an activity form. Use ArrayList as data source for ArrayAdapter instead of array. It's important because you'll use its "remove" method later

      List<String> reportFiles = new ArrayList<String>();        
      //fill some test data     
      reportFiles.add("aaaaaaaaaaaaa");
      reportFiles.add("bbbbbbbbbbbbb");
      reportFiles.add("ccccccccccccc");
      
      //create spinner from corresponding layout xml file
      Spinner spnReport  = (Spinner) findViewById(R.id.spinner_report);
      
      //create ArrayAdapter
      ArrayAdapter reportAdapter =  new ArrayAdapter(this, 
              android.R.layout.simple_spinner_dropdown_item,  reportFiles);
      
      //set adapter to spinner
      spnReport.setAdapter(reportAdapter);
      
      //select first item in adapter - is not obligatory
      spnReport.setSelection(0);
      
    2. Remove selected item from Spinner

      reportFiles.remove((String)spnReport.getSelectedItem());

      //create new ArrayAdapter with modified ArrayList reportAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,reportFiles);

      //set new array adapter to spinner spnReport.setAdapter(reportAdapter);

      //select first item spnReport.setSelection(0);

    0 讨论(0)
提交回复
热议问题