开发者

Questions about Android ListViews and ArrayAdapters

So I'm toying with this code here, and the main objective is to update a list with a new item once I click a button. The code I have works, but I'm not sure if it's the right way to do it.

I have two methods. The first method takes my ArrayList, add's two strings and posts it to the listview. Great!

The Second method I have is called when I tap on a button. It add's a new string and updates the list, but in order for me to update the existing listview, I had to do the "setListAdapter(new ArrayAdapter...." line again and I'm not sure if that's the right thing to do.

I can use some input please, thanks!

Method 1:

static final List list = new ArrayList();
private void showEvents (Cursor cursor){
        list.add("foo");
        list.add("bar");
        Lo开发者_Go百科g.d(TAG,"showevent");
        setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));



    }

Method 2 (this is called when I tap a button that is under the listView):

private void updateListView(){
        try{
            list.add("son");
            setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));


        }catch (Exception e){
            Log.d(TAG, "E="+e);
        }
    }


Rather than setting the list adapter again, call the notifyDataSetChanged() on the ArrayAdapter. The above will "work", but it forces the entire ListView to redraw, so if you have a long list and the user has scrolled it'll pop them back to the top. The notify is a cleaner way to do that.

Very simple code. I've got a reference to the array adapter in the activity in this case:

adapter.notifyDataSetChanged();

Here's and example based on your code:

static final List list = new ArrayList();
ArrayAdapter adapter;

private void showEvents (Cursor cursor){
    list.add("foo");
    list.add("bar");
    Log.d(TAG,"showevent");

    adapter = new ArrayAdapter<String>(this, R.layout.singleitem, list)
    setListAdapter(adapter);
}

private void updateListView(){
    try{
        list.add("son");
        adapter.nofityDataSetChanged();
        // not needed anymore
        //setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list));
    }catch (Exception e){
        Log.d(TAG, "E="+e);
    }
}


declare a member variable for the ArrayAdapter (say myAdapter) and then initialise it in the showEvents method and set it to the listView. next in the updateListView method after adding string to your list just call myAdapter.notifyDataSetChanged(); and that should do the trick

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜