开发者

ArrayAdapter : Remove by Index

I have a ListView that is populated by a news server rundown (just a list of story slugs) and an arrayAdapter to modify that ListView.

I can remove items by the 'remove(Object)' function but what if there are multiple instances of 'Object'? remove() only removed the first instance of 'Object'. I cannot remove, for example, the second 'Object' in my array adapter without removing the first one. So my question is how can i work around this?

ex : Rundown A

story 1 
story 2
Break
story 3
story 4
Break
story 5
etc...

so in this example i cannot delete the Second 'Break' because remove('Break') will remove the first one. if i could removeByIndex(5), that would be perfect but....

Ive tried writing my own remove function that creates a whole new adapter with all members but the specified index. here is what i was messing around with.

public ArrayAdapter<开发者_如何学运维;String> removeIndex(ArrayAdapter<String> arr, int index) {
    ArrayAdapter<String> temp = new ArrayAdapter<String>(arr.getContext(),R.layout.list_item);
    for(int i =0 ; i<arr.getCount();i++){
        if(i != index) temp.add(arr.getItem(i));
    }
    return temp;
}

Help or suggestions are appriciated.


Handle the collection of strings yourself with a List and pass the object into the constructor of the ArrayAdapter. This leaves you with a reference to the List so you can alter the data while allowing the adapter to manage and display as needed.

Note: When modifying the data object you must call

myAdapter.notifyDataSetChanged()

afterwards - which must also be on the UI thread. Obviously the changes to the list don't have to take place on the UI thread and should most likely not happen on the UI thread.

private ArrayList<String> mData = new ArrayList<String>();
private ArrayAdapter<String> mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    // Code that adds the strings
    // Create the list adapter
    mAdapter = new ArrayAdapter<String>(myActivity.this, android.R.layout.simple_list_item_1, mData);
}

private void removeItem(int index) {
    mData.removeAt(index);
    myActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            mAdapter.notifyDataSetChanged();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜