Step #4: Returning to the Display Fragment

The “nothing seems to happen” bit from the preceding step is a problem. Usually, when the user clicks a “save” option in an app, not only does the data get saved, but the user is taken to some other portion of the app. In the case of EditFragment, we could send the user back to the DisplayFragment that they came from.

With that in mind, add this navToDisplay() function to EditFragment:

  private fun navToDisplay() {
    findNavController().popBackStack()
  }

This simply “pops the back stack”, doing the same thing as if the user pressed the device BACK button or clicked the “up” arrow in the app bar.

Then, add a call to navToDisplay() from save():

  private fun save() {
    binding?.apply {
      val model = motor.getModel()
      val edited = model?.copy(
        description = desc.text.toString(),
        isCompleted = isCompleted.isChecked,
        notes = notes.text.toString()
      ) ?: ToDoModel(
        description = desc.text.toString(),
        isCompleted = isCompleted.isChecked,
        notes = notes.text.toString()
      )

      edited.let { motor.save(it) }
    }

    navToDisplay()
  }

If you run the sample app now, when you click “save” in the EditFragment, you go back to the DisplayFragment.

However, if you are using a device with a soft keyboard, that soft keyboard may still be visible after clicking “save”. This is annoying. But, with some trickery, we can fix it.

Add this function to EditFragment:

  private fun hideKeyboard() {
    view?.let {
      val imm = context?.getSystemService<InputMethodManager>()

      imm?.hideSoftInputFromWindow(
        it.windowToken,
        InputMethodManager.HIDE_NOT_ALWAYS
      )
    }
  }

This method, based on this Stack Overflow answer, hides the soft keyboard (a.k.a., “input method editor”). This code is clunky but is unavoidable. Basically, we get the InputMethodManager system service and call hideSoftInputFromWindow() on it. Note that the getSystemService() function we are using is an extension function provided by Android KTX, the Kotlin extension functions supplied by the Jetpack:

import androidx.core.content.getSystemService

Then, modify navToDisplay() in EditFragment to call hideKeyboard():

  private fun navToDisplay() {
    hideKeyboard()
    findNavController().popBackStack()
  }

Now, if you run the sample app and edit a to-do item, saving your changes both returns you to the DisplayFragment and hides the soft keyboard if needed.

However, we still do not see the changes from our edits. The list appears as it did originally.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.