3

I have some strange requirements where I have to keep the keyboard open when moving to the next fragment in the user onboarding flow. I tried to implement that using one invisible EditText inside the parent activity layout file and requesting focus to this EditText just before loading the next fragment but no luck with that.

In SO, I found all the issues related to not closing the keyboard when changing fragments but I specifically need that issue as a feature inside our app onboarding.

I am using the Jetpack Navigation component to navigate in between fragments and all fragments are used in the same activity.

Bipin Vayalu
  • 3,025
  • 2
  • 25
  • 39

2 Answers2

1

Please have a look to the fragment life cycler and use them. suppose you've 2 fragments A & B. OnCreate() or OnCreatView() of B Fragment, show the keyboard everytime.

for lifecycle of fragment: https://developer.android.com/guide/fragments/lifecycle

this can also help you: https://stackoverflow.com/a/32177634/10705803

Muhammad Ali
  • 1,055
  • 6
  • 11
  • Yes, I already tried that but it's giving a close and quickly open effect in fragment B. I want to keep it open while fragment transition. – Bipin Vayalu Sep 01 '21 at 11:25
1

you should add destinationchanged listener and hide keyboard after any navigation happens.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    findNavController(R.id.mainNavHostFragment).addOnDestinationChangedListener(this)
}


override fun onDestinationChanged(
        controller: NavController,
        destination: NavDestination,
        arguments: Bundle?
) {
    currentFocus?.hideKeyboard()
}

fun View.hideKeyboard() {
    val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}
Arvin Rezaei
  • 818
  • 10
  • 25