3

I noticed that when I use keypad navigation in my apps to focus on items in a RecyclerView, the focus gets transferred outside the RecyclerView after changing the screen orientation.

By comparison, ListView always restores the focused item properly.

Is it the intended behavior and if not, how can I fix it?

BladeCoder
  • 11,697
  • 2
  • 51
  • 46
  • Does your adapter has stables ids? Where are you creating and setting adapter?(i mean where in activity/fragment lifecycle) – Selvin Dec 20 '16 at 14:37
  • I tested with and without stable ids. I create and set the adapter in Fragment.onActivityCreated(). The scroll position is restored properly. The focus is not. – BladeCoder Dec 20 '16 at 14:52

1 Answers1

0

It does not do that by default. You may store the focused position in Activity's or Fragment's onSaveInstanceState method inside a bundle, restore in onCreate/onViewCreated.

Here's how to do this.

Community
  • 1
  • 1
R. Zagórski
  • 18,351
  • 5
  • 59
  • 86
  • 1
    Thank you for your reply. It's a bit trickier than that to handle manually. You can not focus an item view until it's created during the next layout pass. RecyclerView performs layout asynchronously. So you would need to save the focus position in the adapter and call requestFocus() when onViewAttachedToWindow() is called for that position. – BladeCoder Dec 20 '16 at 15:01