简体   繁体   中英

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 ?

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)
    }
}

This should work(i`m using it in OnClickListeners usually):

    InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM