![](https://kiranofans123.wordpress.com/wp-content/uploads/2020/08/activity_fragment_transition-2.png?w=1024)
It’s actually pretty easy when you understand the logic.
- The Transition name must be the same.
There are two ways to get the transition name (or maybe 3)1. Use ViewCompat.getTransitionName([view that has the transition name],[the transition name])
2. Call setTransitionName() on devices running Lollipop and up.
3. Add element to strings.xml in value folder, and reuse it. - If you want to make transition in an Activity, you should put following line first before the super.onCreate(savedInstanceState) in onCreate(Bundle savedInstanceState)
@Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); super.onCreate(savedInstanceState); }
Then, in the function that performs transition, put similar code below:
@Override private void performTransition(){ Fade exitFade = new Fade(); exitFade.setDuration(FADE_DEFAULT_TIME); getWindow().setExitTransition(exitFade); //Here you can use Fade or Explode class ... }
- If you want to make transition from Activity to another activity, add below code to start the other activity:
@Override private void performTransition(){ Fade exitFade = new Fade(); exitFade.setDuration(FADE_DEFAULT_TIME); getWindow().setExitTransition(exitFade); //Here you can use Fade or Explode class ... Intent activityIntent = new Intent(this,anotherActivity.class); activityIntent.putExtra(key,value); startActivity(intent,ActivityOptionsCompat.makeSceneTransitionAnimation(this).toBundle()); //You can use ActivityOptinsCompat or just ActivityOptions }
You can also set return transition by calling setSharedElementReturnTransition(new Fade());
- Transition with fragment is almost the same, and you don’t have to write down the getWindow().requestFeature()
private void performTransition(){ Fade exitFade = new Fade(); exitFade.setDuration(FADE_DEFAULT_TIME); fragmentInstance.setExitTransition(exitFade); //And; you can put a ViewGroup id of either an activity or fragment FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.addSharedElement(mBinding.articleImgViewContent,transName) .replace(R.id.article_root_view,imgFragment).addToBackStack(null) .commitAllowingStateLoss();//commit() or commitAllowingStateLoss() }
- In the AnnotherActivity.java, get the transition name, and extra data:
private void setTransition(){ String transName = ViewCompat.getTransitionName(imgBinding.imageFragmentContainer); ViewCompat.setTransitionName(imgBinding.imageFragmentContainer,transName); Glide.with(this).load(articleMod.getUrlToImage()).into(imgBinding.fullImageView); }
Run it in onCreate(), this can be applied to Fragments as well. And don’t forget to put getWindow().requestFeature() before super.onCreate()
And that’s all!