Ivan Vetrugno
Ivan Vetrugno

Reputation: 63

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

i've a problem in my Android app.

I have a fragment that is generated as a list of editable textview. Every textview has a setOnFocusChangeListener that calls an API on server. FocusChangedListener works correctly on last textview, and after that my textview remain focused as you can see in the figure below.

enter image description here

Problem

Now i have to change menu (fragment) by clicking on the right menu button. When button is clicked and the new menu is about to be loaded, my textview loses focus and calls the API, but i don't want my app do that. If I click menu button is because i've to change it and i expect that my old fragment disappear or basically don't execute the FocusChangedListener.

enter image description here

Any ideas?

Upvotes: 2

Views: 295

Answers (2)

Ivan Vetrugno
Ivan Vetrugno

Reputation: 63

I made a little trick to solve the problem. I just added this code inside OnCreate of my DrawerMenu and then i set a Global Variable "drawerOpened" to check every time if my Menu is open or not.

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

Then in my HomeFragment i did this:

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

This is not a complete solution, but it works fine.

Upvotes: 1

kirkadev
kirkadev

Reputation: 348

I assume that after a click, the application switches to touch mode and your EditText loses focus. It happens at the system level.

A focus can have only one view at a time.

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

Upvotes: 0

Related Questions