过滤ListView点击跳转错误:打开错误Intent问题求助
问题分析与解决方案:过滤后ListView点击打开错误Intent
嘿,我一眼就看出问题的核心了!你现在的点击事件里依赖的是原始的aphashmap,但这个hashmap并没有跟着你的ListView过滤结果同步更新。当列表过滤后,position对应的是过滤后列表的索引,可aphashmap还是保留着原始数据的顺序,所以你拿到的ProductID自然是错的。
下面给你两种解决方案,推荐第一种,更简洁可靠:
方案1:直接从Adapter获取过滤后的Item(强烈推荐)
你的Adapter已经正确维护了过滤后的filteredList,而且getItem(position)方法返回的就是对应位置的正确数据,完全没必要再依赖外部的hashmap。修改你的点击事件代码就行:
lvsearch.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 获取当前Adapter实例 Searchitemadapter adapter = (Searchitemadapter) parent.getAdapter(); // 拿到过滤后的对应商品对象 B_allProducts targetProduct = (B_allProducts) adapter.getItem(position); // 从对象里直接取ProductID(假设你的B_allProducts类有这个getter方法) String productId = targetProduct.getProductID(); Intent i = new Intent(SearchableActivity.this, DisplaySingleProduct.class); i.putExtra("ProductID", productId); startActivity(i); } });
方案2:同步更新aphashmap(不推荐,冗余)
如果你非要保留aphashmap的使用,那得让它和Adapter的filteredList同步更新。不过这种方式会增加代码耦合和冗余数据,不太推荐:
你需要修改Adapter的publishResults方法,同步更新外部的aphashmap:
@SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { filteredList = (ArrayList<B_allProducts>) results.values; // 清空旧的hashmap,同步过滤后的新数据 aphashmap.clear(); for (int i = 0; i < filteredList.size(); i++) { B_allProducts product = filteredList.get(i); // 按照你原始aphashmap的结构,把当前商品的信息放进去 HashMap<String, String> productMap = new HashMap<>(); productMap.put("ProductID", product.getProductID()); // 其他需要的字段也可以同步放进来 aphashmap.put(i, productMap); } notifyDataSetChanged(); }
注意:这种方式需要让Adapter能访问到aphashmap,要么把它设为全局变量,要么在Adapter构造方法里传入,会增加代码耦合度。
额外小优化:修复Adapter构造方法的潜在问题
你的Adapter构造方法里直接把filteredList = friendList,这会让两个列表引用同一个对象,过滤操作可能会意外修改原始的friendList数据。改成复制列表更安全:
public Searchitemadapter(Home activity, ArrayList<B_allProducts> friendList) { this.activity = activity; // 复制原始列表,避免引用同一对象 this.friendList = new ArrayList<>(friendList); this.filteredList = new ArrayList<>(friendList); getFilter(); }
内容的提问来源于stack exchange,提问作者Masoom Badi
相关产品推荐
相关产品推荐

