Skip to content Skip to sidebar Skip to footer

Need An Explanation Why Recyclerview.adapter.notifyitemchanged(int Position, Object Payload) And I Bind Payload Parameter Is List Of Objects

RecyclerView.Adapter.notifyItemChanged(int position, Object payload), where payload is an arbitrary object that will be passed to RecyclerView.Adapter.onBindViewHolder(VH holder, i

Solution 1:

Well, there is a concept of Partial and Full binding in recycler view. This is what Android Developers site says about the onBindViewHolder method:

The payloads parameter is a merge list from notifyItemChanged(int, Object) or notifyItemRangeChanged(int, int, Object). If the payloads list is not empty, the ViewHolder is currently bound to old data and Adapter may run an efficient partial update using the payload info. If the payload is empty, Adapter must run a full bind. Adapter should not assume that the payload passed in notify methods will be received by onBindViewHolder(). For example when the view is not attached to the screen, the payload in notifyItemChange() will be simply dropped.

Reading this will help: onBindViewHolder - Android Developers

Solution 2:

You can use payloads with also DiffUtils or with notifyItemChanged(int position, @Nullable Object payload)

The point of payload of being an Object/Any class of list to have different kind of objects depending on scenario you have.

For instance let's say your recycler view items contain image, title as string and price as number, or any other values depending on situation.

When some fields in your data change when onBindViewHolder is called without payload, and you have a big image you have a flickering which bothers users.

Instead you check and send payload depending on which data changed. If only title has changed you put a String inside this list, if number has changed you can put Int to list[0]. If both change you can put title to list[0] and price to list[1] and check for that situation. String and Int are simple variables and no need to send Int instead of String but these are for the sake of the argument, you can have different items in payloads.

overridefunonBindViewHolder(
    holder: CustomViewHolder<CurrencyRateEntity>,
    position: Int,
    payloads: MutableList<Any>
) {


    if (payloads.isNullOrEmpty()) {

        // Set item binding as whole since no payload
        binding.setVariable(BR.item, item)
        binding.executePendingBindings()

    } else {

        when (val payload = payloads[0]) {
            is String -> {
                title.setText = payloads[0]
            }
            isInt -> {
                // do something with int
                price.text =  "${payload / 1000}"
            }
        }
    }

    super.onBindViewHolder(holder, position, payloads)
}

Post a Comment for "Need An Explanation Why Recyclerview.adapter.notifyitemchanged(int Position, Object Payload) And I Bind Payload Parameter Is List Of Objects"