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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With