如何使用自定义数组适配器删除自定义列表中的特定列表项(列表行)?

时间:2015-10-21 10:29:09

标签: android listview android-arrayadapter

我是Android的新手,我正在开发一个应用程序,我正在扫描NFC卡并将结果的NFC字符串与列表中的值进行匹配。 所以我想要的是当NFC的结果与任何列表项匹配时,应该删除匹配的列表项(列表行)。 以下是自定义列表视图的代码:

public class Item {
     private String StdName;
     private String Id;
     private int img;

public Item() {

}

public Item(String name, String id, int img) {
    this.StdName = name;
    this.Id = id;
    this.img = img;
}
//getters & setters...
 ...
}

并使用自定义数组适配器

 public class ItemAdapter extends ArrayAdapter<Item>

将元素添加到列表中,如下所示:

 private ArrayList<Item> m_parts = new ArrayList<Item>();
 m_parts.add(new Item(StdntId, StudentName, R.drawable.cancel));
 m_adapter = new ItemAdapter(MainActivity.this, R.layout.list_row, m_parts);
 listView.setAdapter(m_adapter);

我需要查找列表项的索引,其中Id(列表项中的字段)与NFC字符串匹配,以便我可以按索引删除列表项。 主要问题是比较结果字符串,例如&#34; 2&#34;用&#34; id&#34;自定义数组列表中的字段,即m_parts,它有3个字段,如(String id,String name,integer img)。所以我想匹配我从感知nfc标签获得的字符串&#34; id&#34; m_parts array-list中的字段请帮助/指导我完成任务。

感谢!!!

2 个答案:

答案 0 :(得分:3)

您需要从列表中删除该项目,然后告诉适配器它已被删除,如下所示:

this.m_parts.remove(position);
notifyItemRemoved(position);

获得职位的逻辑取决于代码的其余部分如何运作。

要匹配你的字符串,只需遍历每个项目并查看它是否匹配,如果匹配,则删除/删除它。像这样:

public void checkAndDeleteMatchingIds(String idToMatch) {
    for (int i = 0; i < m_parts.size(); i++) {
        if (m_parts.get(i).getId().equals(idToMatch)) {
            removePart(i);
        }
    }
}

public void removePart(int position) {
    this.m_parts.remove(position);
    notifyItemRemoved(position);
}

上面的代码会放在您的适配器中,扫描时调用checkAndDeleteMatchingIds。

答案 1 :(得分:2)

            private static IDictionary<DriveInfo, string> GetMappedNetworkDrives()
        {
            var rawDrives = new IWshRuntimeLibrary.IWshNetwork_Class()
                .EnumNetworkDrives();
            var result = new Dictionary<DriveInfo, string>(
                rawDrives.length / 2);
            for (int i = 0; i < rawDrives.length; i += 2)
            {
                result.Add(
                    new DriveInfo(rawDrives.Item(i)),
                    rawDrives.Item(i + 1));
            }
            return result;
        }
相关问题