Элемент списка Recyclerview будет перемещен к следующему элементу после удаления - PullRequest
0 голосов
/ 12 января 2020

У меня есть Recyclerview с продуктами. Каждый продукт имеет уведомление, которое вы можете добавить через AlertDialog. После удаления предмета следующий предмет получит уведомление об удаленном предмете, если у него его нет. Это, вероятно, как-то связано со ссылкой. Но я не знаю где. Я пытался создать новый продукт вместо make products [position], но это не сработало.

Вот мой onBindViewHolder:

override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
        val product = products[position]

        //render
        val imgUrl = BASE_IMG_URL + product.images.small[0]
        Glide.with(viewHolder.image.context).load(imgUrl).into(viewHolder.image)

        viewHolder.title.text = product.name
        viewHolder.subtitle.text = product.prodid
        viewHolder.quantity.text = product.quantity.toString()

        viewHolder.close.setOnClickListener {
            products.removeAt(position)
            notifyDataSetChanged()
            viewModel.updateProducts(products)
        }

        viewHolder.cart_product_add_notice.setOnClickListener {
            showProductNoticeDialog(it, product, viewHolder)
        }

        if(product.notice.isNotEmpty()) {
            if(product.notice.length >= 20) {
                viewHolder.cart_product_notice.text = product.notice.substring(0,30) + "..."
            } else {
                viewHolder.cart_product_notice.text = product.notice
            }
        }
    }

Функция showProductNoticeDialog () будет обрабатывать setOnClickListener:

fun showProductNoticeDialog(view: View, product: ProductCart, viewHolder: ViewHolder) {
        // get alert_dialog.xml view
        val li = LayoutInflater.from(view.context)
        val promptsView = li.inflate(R.layout.alert_dialog_product_notice, null)

        val alertDialogBuilder = AlertDialog.Builder(
            view.context
        )

        // set alert_dialog.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView)

        val alertDialog = alertDialogBuilder.create()

        val userInput = promptsView.findViewById(R.id.alert_user_input) as EditText

        if(product.notice.isNotEmpty()) {
            userInput.setText(product.notice)
            userInput.setSelection(userInput.text.length)
        }

        val okayBtn = promptsView.findViewById<Button>(R.id.btn_alert_dialog_notice_okay)
        val cancelBtn = promptsView.findViewById<Button>(R.id.btn_alert_dialog_notice_cancel)

        okayBtn.setOnClickListener {
            product.notice = userInput.text.toString()

            if(userInput.text.length >= 20) {
                viewHolder.cart_product_notice.text = userInput.text.substring(0, 30) + "..."
            } else {
                viewHolder.cart_product_notice.text = userInput.text
            }

            alertDialog.cancel()
        }

        cancelBtn.setOnClickListener { alertDialog.cancel() }

        alertDialog.show()
    }

Я надеюсь, что кто-то может мне помочь:)

1 Ответ

1 голос
/ 12 января 2020

Как сказано @gpunto в комментарии, RecyclerView повторно использует то же представление после обновления списка. Решение в этом случае состоит в том, чтобы установить уведомление пустым, если оно отсутствует, чтобы очистить его, если оно было установлено до

    if(product.notice.isNotEmpty()) {
        if(product.notice.length >= 20) {
            viewHolder.cart_product_notice.text = product.notice.substring(0,30) + "..."
        } else {
            viewHolder.cart_product_notice.text = product.notice
        }
    }
    else {
            viewHolder.cart_product_notice.text = ""
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...