Android/Kotlin - 通过按导航菜单按钮失去对文本字段的关注后片段未附加到 Activity

Android/Kotlin - Fragment not attached to Activity after loosing focus on textfield by pressing navigation menu button

我的 Android 应用程序有问题。

我有一个生成为可编辑文本视图列表的片段。每个文本视图都有一个 setOnFocusChangeListener 调用服务器上的 API。 FocusChangedListener 在最后一个 textview 上正常工作,之后我的 textview 保持聚焦,如下图所示。

问题

现在我必须通过单击右侧的菜单按钮来更改菜单(片段)。 单击按钮并且即将加载新菜单时,我的文本视图失去焦点并调用 API,但我不希望我的应用程序那样做。如果我单击菜单按钮是因为我必须更改它并且我希望我的旧片段消失或者基本上不执行 FocusChangedListener。

有什么想法吗?

我假设在单击之后,应用程序切换到触摸模式并且您的 EditText 失去焦点。 它发生在系统级别。

一个焦点一次只能有一个视图。

https://android-developers.googleblog.com/2008/12/touch-mode.html

我做了一个小技巧解决了问题。 我刚刚在我的 DrawerMenu 的 OnCreate 中添加了这段代码,然后我设置了一个全局变量“drawerOpened”来检查我的菜单是否打开。

        // Initialize the action bar drawer toggle instance
    val drawerToggle:ActionBarDrawerToggle = object : ActionBarDrawerToggle(
        this,
        drawer_layout,
        toolbar,
        R.string.navigation_drawer_open,
        R.string.navigation_drawer_close
    ){
        override fun onDrawerClosed(view:View){
            super.onDrawerClosed(view)
            GlobalVar.drawerOpened = false
        }

        override fun onDrawerOpened(drawerView: View){
            super.onDrawerOpened(drawerView)
            GlobalVar.drawerOpened = true
            currentFocus?.clearFocus()  //clear focus - any view having focus
        }
    }

然后在我的 HomeFragment 中我这样做了:

// if GlobalVar.drawerOpened is false then setOnFocus

if (field.validatefield || field.nextpage != 0)
{
  textView.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus && !GlobalVar.drawerOpened)
    {
        if ((field.mandatory && !textView.text.toString().isNullOrEmpty()) || (!field.mandatory)) {
            if (field.validatefield) {
                validateField(field.fieldcode, textView.text.toString(), field.nextpage)
            } else {
                _goToNextPageNo = field.nextpage
                goToNextPageIfExist()
            }
        }
    }
  }
}

这不是一个完整的解决方案,但效果很好。