ArrayAdapter:按索引删除 [英] ArrayAdapter : Remove by Index
问题描述
我有一个由新闻服务器摘要填充的ListView(只是一个故事素材列表)和一个arrayAdapter来修改该ListView.
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.
我可以通过'remove(Object)'函数删除项目,但是如果有多个'Object'实例怎么办? remove()仅删除对象"的第一个实例.例如,如果不删除第一个对象,则无法删除阵列适配器中的第二个对象".所以我的问题是我该如何解决?
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:摘要A
story 1
story 2
Break
story 3
story 4
Break
story 5
etc...
因此在此示例中,我无法删除第二个"Break",因为remove('Break')会删除第一个"Break".如果我可以removeByIndex(5),那将是完美的,但是....
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....
我曾尝试编写自己的remove函数,该函数将使用除指定索引之外的所有成员创建一个全新的适配器.这就是我在玩弄的东西.
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;
}
寻求帮助或建议.
推荐答案
使用List自己处理字符串集合,然后将该对象传递给ArrayAdapter的构造函数.这为您提供了对列表的引用,因此您可以更改数据,同时允许适配器根据需要进行管理和显示.
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()
之后
-必须也位于UI线程上.显然,列表的更改不必在UI线程上进行,并且很可能在UI线程上不发生.
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();
}
}
}
这篇关于ArrayAdapter:按索引删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!