![](/img/trans.png)
[英]How to remove an item from ArrayList<HashMap<String, Object>>
[英]How to remove the selected item from Arraylist<HashMap<String, String>> in android
我在ListView中使用Arraylist < HashMap< String, String >>
來歸檔多列(我只需要兩列,所以我使用HashMap)。 但是當我在上下文菜單中使用remove方法時。 它將始終刪除列表中的最后一項。
編碼:
@Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.bc_contextmenu_delete:
list.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
如何解決此問題,以從列表中刪除選定的一個?
此外,我還想從ArrayList中的HashMap中獲得這兩個值。 我應該在這里使用哪個代碼。
這是一個ArrayList:
PS4 4000<br>
PS5 5000<br>
XBOX 6000<br>
我想得到PS4和4000。
謝謝大家
無需將HashMap包裝到ArrayList中。 HashMap本身就足夠了。 如果您想保留訂單,則應使用LinkedHashMap 。 副作用是您無法按索引訪問元素,因此必須對其進行迭代以獲取最后一項或按索引訪問一項。
因此,如果您不關心重復項,則可以將ArrayList與對或自定義對象用作模板。 (在我希望自定義對象更易讀的地方)
ArrayList<Pair<String,String>> consoles = new ArrayList<Pair<String,int>>();
consoles.Add(Pair.create("PS4", 4000));
consoles.Add(Pair.create("PS5 ", 5000));
consoles.Add(Pair.create("XBOX ", 6000));
並刪除使用索引:
consoles.Remove(index);
根據您的要求,您可以為它創建一個bean。 即DummyBean。 它有兩個領域
class DummyBean{
String name;
String val;
--getter setter method
}
使用它到List<DummyBean>
。 將來,如果添加新列,則很容易添加和擴展。
要在ArrayList中的Hashmap中存儲和檢索值,您需要使用鍵存儲HashMap值以標識它們
與您的示例一樣,
PS4 4000
PS5 5000
XBOX 6000
ArrayList<HashMap<String ,String>> list = new ArrayList<>();
// to add item
HashMap<String ,String> val = new HashMap<>();
val.put("GAME", "PS4");
val.put("NUMBER", "4000");
list.add(val); //added to 0th index position
val = new HashMap<>();
val.put("GAME", "PS5");
val.put("NUMBER", "5000");
list.add(val); //added to 1st
// to retrieve ps4 and 400
String forPS4 = list.get(0).get("GAME");
String for4000 = list.get(0).get("4000");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.