Shared element transition from Activity to Fragmen

2019-09-20 02:40发布

问题:

am using this code in my Activity

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        view.setTransitionName("pic");

    ActivityOptionsCompat a=ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,view,view.getTransitionName());

    Intent i3=new Intent(context,MovieInfo.class);
    i3.putExtra("id",view.getId());
    startActivity(i3,a.toBundle());
    }

and in my Fragment Class am using this

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        getActivity().getWindow().setSharedElementExitTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.shared_element_transition));
    }
} 

I also tried Using it in the main activity but not able achieve shared element transition but when i go back to my activity transition is working well implies rest of the code is fine!
Any help would be great thanks!

回答1:

First you need to enable windowContentTrasition in your App Theme in styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <!-- Customize your theme here. -->
  <item name="android:windowContentTransitions">true</item>
  .
  .
</style>

Next add same transitionName property to both shared elements in both the layouts

android:transitionName="transition_name"

In your activity create an intent like this

ActivityOptionsCompat options = ActivityOptionsCompat.
    makeSceneTransitionAnimation(this, view, "transition_name");

Intent intent = new Intent(this, MovieInfo.class); 
startActivity(intent, options.toBundle());