Android Development - Using an ArrayList<String> vs an array of strings with ArrayAdapter
I am new to Android development, and I had a question about an excerpt I read in Commonsware's "The Busy Coder's Guide to Android Development". There is an example where it is constructing a class extending ListActivity, and showing the ability to remove and delete from the list via Context Menus. Prior to setting up an ArrayAdapter with the source of strings for the list, the text says to convert the String array to an ArrayList type, because "we want to be able to change the contents of the list on the fly, and that is much easier if you use an ArrayList rather than a ordinary String array"
I understand this concept IF we were using the ArrayList or String array to manipulate the list directly, but why does that matter if we're using the ArrayAdapter.add/insert/remove methods? Once the ArrayAdapter is created (and from what I understand from that .java file), it turns the source data into a List object whether it is coming from an array or ArrayList.
I tried using the normal array when creating the adapter and I got an error (as expected by what the text said), but I do not understand why. What is the difference between creating 开发者_如何学Pythonan ArrayAdapter with a string array vs an ArrayList...won't it turn it into the same List object anyway? Is there some kind of tie back to the original source variable when trying to add/insert/remove via the adapter?
Sorry for the long question, but thanks in advance.
You can change the original array/arraylist. Then you call notifyDataSetChanged() on the adapter and it updates the list with the new information. If you use an ArrayList, then you can use all of its normal operations to insert/remove data at an arbitary index that you cannot do with an ordinary array of Strings. So the contents of the ListView is very much tied back to the original data source- the contents isn't fixed by the adapter at the time you call myListView.setAdapter(). However, the add, remove, insert etc. methods will cause an error if you try them with an array because the array can't be used like this. The ArrayAdapter will actually convert the String array into an AbstractList object, but which can't be modified.
精彩评论