Why can't one add/remove items from an ArrayAdapter?

前端 未结 7 1179
一整个雨季
一整个雨季 2020-11-29 07:26

I am using an ArrayAdapter to populate the items to list in a android.widget.Spinner. That works all fine.

But now I wa

相关标签:
7条回答
  • 2020-11-29 07:33

    In your adapter Class - Delete an Item

    remove(position);
    notifyDataSetChanged();
    

    Add an Item -

    adapter.add (newItem);
    adapter.notifyDataSetChanged ();
    
    0 讨论(0)
  • 2020-11-29 07:38

    You probably initialized the adapter with a plain Java array (e.g., String[]). Try using something that implements the java.util.List interface (e.g., ArrayList<String>).

    0 讨论(0)
  • 2020-11-29 07:43

    I know it's late but just a quick explanation: it's because method Arrays.asList(T... array) returns custom inner class named ArrayList that is read-only. As already said, you need to provide full impl. e.g. java.util.ArrayList.

    0 讨论(0)
  • 2020-11-29 07:43

    You can try like this:

    new ArrayList<>(Arrays.asList(recentlyClient))
    

    Example code how to implement:

    String[] recentlyClient;
    
    ArrayAdapter<String> recenAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,new ArrayList<>(Arrays.asList(recentlyClient)));
    
    
    0 讨论(0)
  • 2020-11-29 07:46

    Probably, you are using List in your ArrayAdapter class instead of ArrayList.

    Try converting your array or list to ArrayList -

    new ArrayList<ClassType>(Arrays.asList(array));
    
    0 讨论(0)
  • 2020-11-29 07:47

    I was having the same problem, my data was saved in resource String Array, so I was creating ArraAdapter with createFromResource.
    The following code for creating ArrayAdapter from resource String Array solved the problem:

    Resources res = getResources();
    String[] cities = res.getStringArray(R.array.cities_array);
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
         this,
         android.R.layout.simple_spinner_item,
         new ArrayList(Arrays.asList(cities)));
    
    0 讨论(0)
提交回复
热议问题