hillasm
hillasm

Reputation: 103

Why does Android ViewPager2 looses focus when switching between tabs?

I have a ViewPager2 on my Android App. One of the pages contains an EditText field.

The scenario I encountered is as follows:

  1. Set focus on the text field -> keyboard shows
  2. Switch to another page -> keyboard dismisses (the field lost focus)
  3. Go back to the previous tab and set focus on the text field again -> the field will gain focus but immediately the focus would clear. Tapping on the field again will get the focus back.

I prepared a small demo app to demonstrate this issue: https://github.com/hilaza/SwitchTabsBugDemo

I debugged it and what I found was that the ViewPager clears the focus from my page, thinking that a page was selected. Debugging it further I saw that it has something to do with the RecyclerView's didChildRangeChange method which wrongly assumes that something has changed.

Does anyone happen to know why it's happening and what can I do to work around this?

Upvotes: 4

Views: 852

Answers (1)

Flexei Prata
Flexei Prata

Reputation: 153

This is a strange bug happens because of Recycler behaviour. Unfortunately, cannot explain why it happens, but know for sure that this row might help you:

pager.offscreenPageLimit = 1

Or the equivalent in Java. This may help because it disables some of Recycler behaviour. Will be happy if someone explains it better. Faced the same issue and resolved it with this one.

Upvotes: 3

Related Questions