Previous fragment edittext focus issue

Viewed 391

I am using multiple fragments. I am adding fragment over fragment as below

supportfragmentmanager
            .beginTransaction()
            .add(R.id.container_login, newFragment, newFragment.javaClass.simpleName)
            .addToBackStack(newFragment.javaClass.simpleName)
            .commitAllowingStateLoss()

Now the issue is, despite of adding new fragment, previous fragment is not losing focus. Typing in edittext of current fragment types in previous fragment edditext.

Even action next also loses focus in current fragment and moves cursor in previous fragment.

Kindly help.

2 Answers

The fragment does not lose focus because you use .add method which adds the new fragment over the one which already exists in the container. Use .replace() method which replaces the existing fragment from the container. This is similar to calling remove(Fragment) and then use .add() method.

If you want to add a fragment in one container is impossible but if you want to replace the fragment with another fragment is possible to do it, because one layout is for 1 fragment, not more than one, so you just need to replace the previous fragment with another fragment

I have a simple code if you want to replace the previous fragment with the new fragment

First, you need to add one method with the parameter of the fragment

fun openFragment(fragment: Fragment?) {
    val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.container_content, fragment!!)
    transaction.commit()
}

If you want to replace the fragment with another fragment just call the method like this openFragment(FragmentClass.newinstance()) soo the previous fragment will be replaced with the new fragment

I hope this code can help you to solve your problem

Related