我在一项 Activity 中托管了多个 fragment 。当某些 fragment 关闭时,如果打开,则有必要隐藏键盘,这通常是通过将 onOptionsItemSelected 从 Activity 链接到 fragment 来完成的
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
UiUtil.hideKeyboard(activity)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
但是当使用 Navigation Architecture Component 时,它看起来真的很糟糕。 有什么简单的方法可以用导航架构组件隐藏键盘吗?
最佳答案
我想确保我们每次更改目的地时都隐藏键盘。所以我做了这样的事情:
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)
}
}
关于android - 关闭 fragment 时如何使用导航体系结构组件隐藏键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54202178/