繁体   English   中英

从列表视图中动态删除元素 - Android

[英]Dynamically Delete an element from listview - Android

当在列表元素的布局上单击按钮 x 时,我想从列表中删除一个元素。 这是我的 java 代码, onNext() 正在向列表中添加一个元素。 但 onDelete 不起作用。添加新元素时,textView4 元素的数字从 1 到 n

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list2); arrayList = new ArrayList<String>(); arrayList.add("1"); adapter2 = new ArrayAdapter<String>(this, R.layout.list2_layout, R.id.textView4, arrayList); ListView myList2 = (ListView) findViewById(R.id.listView2); myList2.setAdapter(adapter2); } public void onNextItem(View v) { counter++; String str=Integer.toString(counter); arrayList.add(str); adapter2.notifyDataSetChanged(); } public void onDeleteItem(View v2) { arrayList.remove(R.id.textView4); adapter2.notifyDataSetChanged(); }

你不应该通过R.id.textView4来删除第 4 个 textView

 arrayList.remove(R.id.textView4);

您将需要执行类似arrayList.remove(4); 从列表中删除第四个元素

onNextItem(View v)

正在将integer(counter) converted to stringinteger(counter) converted to string添加到列表arrayList.add(str);

但在onDeleteItem(View v2)

您正试图从列表中删除一个viewarrayList.remove(R.id.textView4);

您试图删除 Textview

arrayList.remove(R.id.textView4); 

像这样做

arrayList.remove(clickeditempostion);
adapter2.notifyDataSetChanged();

你可以做这样的事情。

arrayList.remove(CURRENT_INDEX_OF_ARRAYLIST);
        adapter2.notifyDataSetChanged();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM