【发布时间】:2016-11-02 12:18:49
【问题描述】:
我创建了一个 ListView,在其中显示来自数据库的一些记录。当有人从 ListView 中单击一个项目时,我需要将该项目从 ListView 中完全删除。如果我使用 view.setVisibility(View.GONE); 或 view.setVisibility(View.INVISIBLE); 任何文字都会消失。我需要删除整个项目。我正在使用 ListAdapter 接口而不是 SimpleAdapter 类。
我该怎么做?这是我的代码:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, showProductsUrl, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("products");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
final String productId = jsonObject.getString("id");
final String productName = jsonObject.getString("productName");
HashMap<String, String> product = new HashMap<>();
product.put(ID, productId);
product.put(PRODUCT_NAME, productName);
productList.add(product);
String[] from = {ID, PRODUCT_NAME};
int[] to = {R.id.id, R.id.productName};
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), productList, R.layout.list_products_to_buy, from, to);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setVisibility(View.GONE);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
提前致谢!
【问题讨论】:
-
您应该从适配器中删除该项目。
-
您将产品存储在“productList”中。您应该从该列表中删除要删除的项目并调用 adapter.notifyDataSetChanged()。
-
@Alex 好的,我该怎么做? @sunilsunny 我尝试使用
productList.remove(position);,但出现错误:java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. -
@Alex M。您需要将 ListAdapter 更改为 SimpleAdapter,然后在从列表中删除元素后调用 notifydatasetchanged 方法。还请考虑塞尔文在其他 cmets 中所说的话。
标签: android listview listadapter