ArrayAdapter : Remove by Index

江枫思渺然 提交于 2019-12-12 21:01:59

问题


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.


回答1:


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();
        }
    }
}


来源:https://stackoverflow.com/questions/6964768/arrayadapter-remove-by-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!