简体   繁体   中英

How to replace fragment in androidx.fragment.app.FragmentContainerView with Android databinding

My current Android application employs databinding.

I having issues when attempting to add a fragment to a androidx.fragment.app.FragmentContainerView .

I have managed to get the effect I was after, however it doesnt feel the correct approach.

I do not understand where I have made a mistake.

in my activity onCreate method I perform this code to set the required fragment

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        if (savedInstanceState == null) manageFragment()
    }

where manageFragment() function resembles this

private fun manageFragment() {
    val myFragment = MyFragment.instance()

    when {
        (currentFragment == null) -> supportFragmentManager
            .beginTransaction()
            .replace(R.id.my_fragment_container, myFragment)
            .commit()

        (currentFragment is MyFragment) -> doNothing()

        else -> supportFragmentManager
            .beginTransaction()
            .replace(R.id.my_fragment_container, myFragment)
            .commit()
    }
}

When I check after manageFragment() this method returns null in onCreate()

supportFragmentManager.findFragmentById(R.id.my_fragment_container)

However when I call the same method in onPostCreate()

override fun onPostCreate(savedInstanceState: Bundle?) {
    super.onPostCreate(savedInstanceState)
    currentFragment = supportFragmentManager.findFragmentById(R.id.my_fragment_container)
}

It has my fragment set

Is this how I should be adding/re[placing fragments when using databinding?

Why doesnt my fragment get returned until postCreate()

Ive a feeling its because once I commit the fragment transaction to add my fragment to the FragmentContainerView , the layout still needs to be measured etc. so "some time" elapses before findFragmentById() can return my added fragment.

is there a layout listener I can add to FragmentContainerView to detect when my fragment is actually added and becomes visible?

Why doesnt my fragment get returned until postCreate()

Commit is asynchronous

is there a layout listener I can add to FragmentContainerView to detect when my fragment is actually added and becomes visible?

Why do you care about this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM