Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide keyboard with Navigation Architecture Component when cloding fragment

I have several fragments hosted in one activity. When some fragments are closed it is necessary to hide keyboard if opened, what is usually done via chaining onOptionsItemSelected from activity to fragment

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            UiUtil.hideKeyboard(activity)
            return true
        }

        else -> return super.onOptionsItemSelected(item)
    }
}

But it looks really bad when Navigation Architecture Component is used. Is there any simple way to hide keyboard with Navigation Architecture Component ?

like image 415
maxxxo Avatar asked Jan 15 '19 15:01

maxxxo


Video Answer


1 Answers

I want to be sure that we hide keyboard everytime when we change destination. So I do something like this:

class MainActivity :
        AppCompatActivity(R.layout.activity_main),
        NavController.OnDestinationChangedListener
{

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

    override fun onDestroy() {
        super.onDestroy()
        findNavController(R.id.mainNavHostFragment).removeOnDestinationChangedListener(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)
    }
}
like image 54
wrozwad Avatar answered Oct 26 '22 23:10

wrozwad