RecyclerView drops to start when requestFocus() is called on item's EditText

Viewed 1192

I have RecyclerView with horizontal LinearLayoutManager and PagerSnapHelper attached.

Item layout is a simple ConstraintLayout with TextView and EditText. When swiping pager I want to move focus to currently visible EditText.

Simplified Item code looks like

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
  ...
  if (data[position].isFocused) {
    editText.post {
       editText.requestFocus()
       editText.showKeyboard()
    }
  }
  ...
}

and RecyclerView scroll listener

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
  override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
    val position = layoutManager.findLastCompletelyVisibleItemPosition()
    if (position == -1)
      return

    // make data[position].isFocused = true and run DiffUtils
    // it is guaranteed that only one item data in adapter has isFocused = true
    adapter.updateFocusedData(position)
  }

The problem is after successful swipe and the requestFocus() call from new current item's EditText makes RecyclerView to drop instantly to the first position.

What am I doing wrong and what way should I dig to understand why is it happening?

1 Answers

Just do this:

adapter.setHasStableIds(true);
Related