如何从列表中删除选中的项目?

How to delete checked items from a list?

我试图在按下删除按钮后根据联系人姓名旁边的复选框从我的联系人列表中删除联系人。现在,当我在列表中有一个联系人时,我能够让代码工作,但是,一旦我添加超过 1 个,它似乎就不起作用,无论我如何调整我的循环。它要么崩溃,我怀疑这与列表中的越界问题有关,要么就我当前的代码而言,它根本不做任何事情。我四处搜索了一些解决方案,但到目前为止,其中 none 已经奏效。如果有人可以帮助我,那将不胜感激。我在当前的实现中包含了下面的相应代码:

MainActivity.kt:

class MainActivity : AppCompatActivity() {

var CONTACT_DETAIL_ACTIVITY_REQUEST = 0

var listContacts = ArrayList<Contacts>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setTitle("Contacts")

    val contactAdapter = DSArrayAdapter(this, R.layout.activity_listview, listContacts)
    val listView1 = findViewById<ListView>(R.id.contact_list)
    listView1.setAdapter(contactAdapter)

    listContacts.add(Contacts("Faisal is spoiled", 732, false))
    listContacts.add(Contacts("Dawg", 666, false))
    contactAdapter.notifyDataSetChanged()

    val add_new_contact = findViewById<Button>(R.id.add_contacts)
    val delete_contacts = findViewById<Button>(R.id.delete_contacts)

    //*** Delete Function ***///
    delete_contacts.setOnClickListener({
        var newlistContacts = ArrayList<Contacts>()
        for (x in listContacts) {
            if (x.cchecked == false) {
                newlistContacts.add(x)
            }
        }
        listContacts = newlistContacts
        contactAdapter.notifyDataSetChanged()
    })
    //*** Delete Function ***///

    add_new_contact.setOnClickListener {
        val name = ""
        val phone_number = 1
        val relationship = ArrayList<String>()

        val intent1 = Intent(this,ContactDetails::class.java)
        startActivityForResult(intent1, CONTACT_DETAIL_ACTIVITY_REQUEST)
    }
    }
    }

DSArrayAdapter.kt:

    class DSArrayAdapter(context: Context, resource: Int, list: ArrayList<Contacts>) : ArrayAdapter<Contacts>(context, resource, list) {
    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    override fun getView(position: Int, convertView: View?, parent: ViewGroup) : View {
    val rowView = inflater.inflate(R.layout.activity_listview, null)
    val item_name = rowView.findViewById<TextView>(R.id.contact_name)
    val item_checkbox = rowView.findViewById<CheckBox>(R.id.checked)

    item_name.setText(getItem(position)?.cname.toString())

    item_checkbox.setOnClickListener(View.OnClickListener{
            val contact = getItem(position) as Contacts
            contact.cchecked = !contact.cchecked
            item_checkbox.isChecked = contact.cchecked
    })

    return rowView
    }
    }

您正在更改联系人列表

listContacts = newListContacts

但是你的适配器不知道newListContacts。 您可以复制调用 listContacts.clear() 和 listContacts.addAll(newListContacts) 但是,如果您复制列表,这将是很多工作。

尝试将您的删除块更改为:

delete_contacts.setOnClickListener({
  listContacts.removeIf { it.cchecked }
  contactAdapter.notifyDataSetChanged()
})