简体   繁体   中英

How to change single item in recycler view without screen reload?

I have Recycler View with a lot of items in. What I want to do is to change the text in TextView inside item that was clicked. I did it in that way:

        wordList.set(position, newWord);
        MyProgressActivityAdapter newAdapter = new MyProgressActivityAdapter(wordList, this);
        newAdapter.notifyItemChanged(position);
        recyclerView.setAdapter(newAdapter);

And everything works fine except of the fact that the screen goes to the top every time I click item. What can I do to avoid that?

You should use the payload version of notifyItemChanged , here is a simple example for you to get the hang of it:

adapter.notifyItemChanged(position, "updateText");

And then in your RecyclerAdapter override the payload version of onBindViewHolder :

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List payloads) {
    if (payloads.isEmpty()) onBindViewHolder(holder, position);
    else if ("updateText".equals(payloads.get(0))) {
        if (holder instanceof YourViewHolder) {
            ((YourViewHolder) holder).textView.setText(dataProvider.get(position).getNewText());
        }
    }
}

Note that this approach prevents RecyclerView from creating a new ViewHolder and then binding your data, so you should just call the notifyItemChanged without resetting the adapter and so.

notifyItemChanged(position) should work if you handle it correctly. Try to handle this inside onBindViewHolder like below:

override fun onBindViewHolder(holder: RecyclerHolder, position: Int) {
    holder.itemView.text_view.text = items[position]

    holder.itemView.button.setOnClickListener {
        items[position] = "New Text"
        notifyItemChanged(position)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM