0

How to create a transition from an Activity to a Fragment?

I specificly tried to create a MaterialSharedAxis transition from an Activity to a Fragment which did not work for me.


Sample Code:

// Activity A

val fragment = Fragment1()
fragment.enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true)
fragment.exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, false)

val fragmentManager = supportFragmentManager
    .beginTransaction()
    .add(R.id.fragment_container_view, Fragment1())
    .addToBackStack("fragment")
    .commit()
// Fragment B

class Fragment1 : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true)
        returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false)
    }

    ...
}
3
  • 1
    The phrase “transition from activity to fragment” doesn’t make sense because a fragment is a piece of an activity. You can begin hosting a fragment in the same activity, or you can transition to another activity that hosts the fragment you want to show. It looks like you are doing the first, but you are loading an instance of the Fragment class instead of the AiFragment class that you created. But either way, it doesn’t have any content to show so the appearance of the fragment will be invisible.
    – Tenfour04
    Commented May 19 at 23:36
  • @Tenfour04 Thank you for your prompt response. I have corrected the sample code. The fragment does display an entire layout. However, only the content inside this layout will have a transition animation applied. The content of the activity does not. Commented May 21 at 8:57
  • That is expected. You are hosting Fragment1 inside your ActivityA. If you want the entire layout to change, there are two choices. The first would be to move all of your current layout from ActivityA into a new Fragment, let’s call it Fragment0. Then make ActivityA’s entire layout only a fragment container and give it Fragment0 as its initial layout. The second way to do it would be to create a second activity that will host Fragment1 and got to the second activity. But the first way is usually preferred.
    – Tenfour04
    Commented May 21 at 11:13

0