Shared element activity transition on android 5

前端 未结 12 609
我寻月下人不归
我寻月下人不归 2021-01-30 13:20

I wanted to setup a shared element transition when going from one Activity to another.

The first Activity has a RecyclerView with items. When an item is clicked that it

12条回答
  •  醉话见心
    2021-01-30 13:58

    What I came up with is to avoid transitioning back to Activity with RecyclerView, or changing back transition with something else.

    Disable all return transitions:

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void finishAfterTransition() {
        finish();
    }
    

    Or, if you want to disable only shared elements return transition, and be able to set your own return transition:

    // Track if finishAfterTransition() was called
    private boolean mFinishingAfterTransition;
    
    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFinishingAfterTransition = false;
    }
    
    public boolean isFinishingAfterTransition() {
        return mFinishingAfterTransition;
    }
    
    @Override
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void finishAfterTransition() {
        mFinishingAfterTransition = true;
        super.finishAfterTransition();
    }
    
    public void clearSharedElementsOnReturn() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            TransitionUtilsLollipop.clearSharedElementsOnReturn(this);
        }
    }
    
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static final class TransitionUtilsLollipop {
    
        private TransitionUtilsLollipop() {
            throw new UnsupportedOperationException();
        }
    
        static void clearSharedElementsOnReturn(@NonNull final BaseActivity activity) {
            activity.setEnterSharedElementCallback(new SharedElementCallback() {
    
                @Override
                public void onMapSharedElements(final List names,
                        final Map sharedElements) {
                    super.onMapSharedElements(names, sharedElements);
                    if (activity.isFinishingAfterTransition()) {
                        names.clear();
                        sharedElements.clear();
                    }
                }
            });
        }
    

    With that implemented in base activity, you can easily use it in onCreate()

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        clearSharedElementsOnReturn(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // set your own transition
            getWindow().setReturnTransition(new VerticalGateTransition());
        }
    }
    

提交回复
热议问题