Home > Software design >  Android - requestFocus to off screen element in recyclerView
Android - requestFocus to off screen element in recyclerView

Time:10-25

I am trying to scroll and request focus to an off screen element from a recycler view. I have a list of 15 languages. When app starts the user can select one language from the recycler. Then if the app starts again the recycler scrolls and request focusto that item.

But imagine the user selects the last language from the list which is not showed in the recycler when the app starts. How to scroll and therefore reqeust focus to that element which is not currently showed in the recycler?

I expected to do something like recycler.scrollToPosition(14) and then scrollToPosition(14) , but the index is outof bunds... I guess thats because the element is not created yet. Any idea?

CodePudding user response:

I had similar scenario and below code worked for me:

(rv_your_recycler_view.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(position, offset)

Just set offset to 0 and position to 14, this will get you last item.

P.S. If it doesn't work check if your recyclerview's bottom constraint tied up to parent's bottom.

app:layout_constraintBottom_toBottomOf="parent"

CodePudding user response:

If you try to scroll and set the focus at the same time then it may fail. While the scrolling will proceed, the request for the focus will fail if the item is not yet present in the RecyclerView. (As you state.)

The solution is to separate the two activities. Scroll to the position as you do now, but set the focus when the item is bound to the view holder in the adapter. This will require you to keep track of which item has the focus so that it can be referenced in the adapter.

  • Related