Spinner delete items

后端 未结 4 1986
南笙
南笙 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: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 reportFiles = new ArrayList();        
      //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);

提交回复
热议问题