Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListViews - how to use ArrayAdapter.addAll() function before API 11?

I'm trying update a ListView with an entirely new ArrayList. For API 11 it works great using the addAll(...) method, but this is not available for earlier APIs. I can't figure out how to go about updating an entire list like this for older versions.

ArrayAdapter<String> textList = new ArrayAdapter<String>(listener, R.layout.list_item, stringList);
listener.setListAdapter(textList);

Then later...

textList.clear();
textList.addAll(stringList); <--- works fine for Android 3.0 (API Level 11) and beyond, but not before. 

How did you go about doing this before addAll() was introduced in API 11? Thanks.

like image 363
mattboy Avatar asked Mar 13 '12 01:03

mattboy


People also ask

How do I use ArrayAdapter?

Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view. xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output.

Which is the 3rd argument for ArrayAdapter?

The third parameter is textViewResourceId which is used to set the id of TextView where you want to display the actual text. Below is the example code in which we set the id(identity) of a text view.


1 Answers

Here's the full code block that uses the native addAll() for Android devices with SDK_INT >= 11, and uses the loop workaround for devices with API level less than 11.

@TargetApi(11)
public void setData(List<String> data) {
    clear();
    if (data != null) {
        //If the platform supports it, use addAll, otherwise add in loop
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            addAll(data);
        } else {
            for(String item: data) {
                add(item);
            }
        }
    }
}

The @TargetApi(11) annotation is used with ADT 17 to suppress Lint warnings when you have a <uses-sdk android:minSdkVersion="X"/> in the AndroidManifest.xml where X is less than 11. See http://tools.android.com/recent/lintapicheck for more info.

like image 136
Sean Barbeau Avatar answered Nov 09 '22 03:11

Sean Barbeau