Search code examples
javaandroidandroid-edittextandroid-viewpager

How to handle focus of edittext inside viewpager2


I have a viewpager2 with 5 fragments, and last fragment has Edittext The question is, I want to requestfocus() to my edittext everytime the user choose last fragment.

What I have tried:

  1. Use registerOnPageChangeCallback(), but the problem is, I can't request focus on page change cause it will cause NPE.
  2. Use onresume, onattach etc, None of them called when user change between fragment
  3. Setuservisisiblehint is deprecated

Any Idea for this problem will be appreciate Thank you

EDIT:

I am sorry I forgot to mention

My Viewpager(parent) is in the last fragment of other viewpager2(child). So I have viewpager2(parent) and the last fragment contains my viewpager2(child). When I choose the last fragment of "child" I can set focus to the edittext. But the problem is when I change the "parent" tab, and go back to last fragment that contains "child". I can't tell the "child" to focus again.

Yes Onresume, and onpause work at the "parent's" fragment, not at "child"

Thank you


Solution

  • You can requestFocus , in the onResume method of that last fragment, with Viewpager2 any off screen fragments are capped at onStarted and resumed when fully on screen.

    I'm not sure why you say:-

    Use onresume, onattach etc, None of them called when user change between fragment

    Unless you are talking about the Activity's onResume instead here.

    This behaviour is not well documented but you can see the functionality in the releasenotes https://developer.android.com/jetpack/androidx/releases/viewpager2#1.0.0-alpha06

    FragmentStateAdapter: non-primary-item Fragments are capped at STARTED, and their menuVisibility is set to false.

    and

    https://developer.android.com/jetpack/androidx/releases/viewpager2#1.0.0-beta05

    Fix for ordering of Fragment pause / resume transactions when changing the page (we now always pause the old primary item before resuming the new one). (b/139489059)

    You also say:-

    Setuservisisiblehint is deprecated

    Which is not part of Viewpager2 but the original viewpager and the original viewpager also only resumes the current fragment.