簡體   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