0

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?

Sa1m0n
  • 710
  • 7
  • 14
  • 1
    Is this code inside the onItemClickListener? From the code, it looks like you're initializing a new adapter... You probably don't want to be initializing a whole new adapter every time you change one item. `notifyItemChanged(position)` on the old adapter should be all that you need to do. – h_k Nov 08 '19 at 16:28
  • You're right, I changed my code, but even now screen goes to the top every time I click on single item. – Sa1m0n Nov 08 '19 at 16:34
  • You can try running on the UI thread, as seen by this answer: https://stackoverflow.com/a/17696214/1421014 – h_k Nov 08 '19 at 16:39

2 Answers2

1

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.

Sdghasemi
  • 5,370
  • 1
  • 34
  • 42
0

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)
    }
}
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46