Search code examples
androidandroid-adapterpayload

Recyclerview adapter onBindViewHolder payload is not working


I checked all the examples, but they don't work after all. As far as I know, even if payload is 'List', String or Int value can go into.

class RecordListAdapter (val context: Context, val layoutManager: LinearLayoutManager, private val canBeEdited: Boolean)
    : RecyclerView.Adapter<RecordListAdapter.RecordViewHolder>() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var records: ArrayList<Record> = arrayListOf()

    // Update ALL VIEW holder
    override fun onBindViewHolder(holder: RecordViewHolder, position: Int) {
        val current = records[position]

        holder.autoCompleteTextView.text = SpannableStringBuilder(current.name)
        holder.weightPicker.value = current.weight
        holder.setPicker.value = current.set
        holder.repsPicker.value = current.reps

        if(position == itemCount - 1) holder.addBtn.visibility = View.VISIBLE
        else holder.addBtn.visibility = View.GONE

        if(canBeEdited) {
            if(itemCount == 1) {
                holder.deleteBtn.visibility = View.GONE
            } else {
                holder.deleteBtn.visibility = View.VISIBLE
                holder.deleteBtn.setOnClickListener {
                    records.remove(current)
                    notifyItemRemoved(position)
                }
            }
        } else
            holder.deleteBtn.visibility = View.GONE
    }

    // Update only part of ViewHolder that you are interested in
    override fun onBindViewHolder(holder: RecordViewHolder, position: Int, payloads: MutableList<Any>) {
        Log.e("payload", "::$payloads")
        if(payloads.isNotEmpty()) {
        } else
            super.onBindViewHolder(holder,position, payloads)
    }

    private fun addRecordDefault() {
        this.records.add(Record("", 28, 5, 10))
        notifyItemInserted(itemCount)
        notifyItemRangeChanged(itemCount-1, 2, "PAYLOAD_ADD_BTN")
    }

    override fun getItemCount() = records.size
}

As above code, I set the Log.e to know whether the value is empty or not. The payload Log.e always say it's null.

E/payload: ::[]


Solution

  • Firstly, it seems you are just adding the item and want to change something in it with payloads right away.
    Obviously, when you just add a new one, the whole item has to be drawn, thus no payloads needed.
    Only then, when it is already drawn and you want to change some elements, you may use payloads with notifyItemChanged (if one item was changed) or notifyItemRangeChanged (if several items were changed).

    Secondly, I am not sure regarding the range you use.
    The first argument of notifyItemRangeChanged is the start index.
    The second one is how many items you want to change.

    Thirdly, it's not clear where do you call the addRecordDefault So make sure you called notifyItemChanged or notifyItemRangeChanged with payloads.