Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

Android - RecyclerView - edittext notifyItemChanged keep focus and continue typing

I have a RecyclerView which has an EditText in its items.

For each EditText I have added a textChangeListener.

Whenever the user types a character I want to do an input validation and so I can change the item, for example show red border in case of wrong input etc...

After I do the validation I call:

adapter.notifyItemChanged(itemPosition) 

to update the view.

But the problem is that the focus is lost from the EditText and I have to click again inside the box in order to continue typing.

Is there a solution for this case? How can I continue typing while the view is updated after calling notifyItemChanged ?

enter image description here

ADAPTER

class ItemAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
     val inflater = LayoutInflater.from(parent.context)
     val binding = LayoutItemBinding.inflate(inflater, parent, false)
     binding.editText.addTextChangedListener {
        // Do layout changes....
        if (isInvalidInput) {
          item.setError = true
          ....
          ...
        }
        
        adapter.notifyItemChanged(itemPosition)
     }
     return ItemViewHolder(binding)
  }

  override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
      holder.bind(items[position])
  }

  inner class ItemViewHolder(val binding: LayoutItemBinding) 
  : RecyclerView.ViewHolder(binding.root) {

      fun bind(model: ItemModel) {
            // Setup view for item
        }
  }

}
question from:https://stackoverflow.com/questions/65832030/android-recyclerview-edittext-notifyitemchanged-keep-focus-and-continue-typi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, Please post your code.

If you called notifyDatasetChanged(), all views of recyclerview will refreshed (it means that the views could be recreated.).

So if you want remain focus in edittext, you not call notifyDatasetChanged() or set focus to your edittext after notifyDataChanged().

But setFocus is bit more difficult. So I suggest method that update views of recyclerview without call notifyDatasetChanged(). I think you can directly update view of recyclerview without call notifyDataChanged().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...