Android reverse shared element transition on back after orientation change?

前端 未结 4 1430
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 14:20

For shared element transition I am following this github project. It has 2 screens - one with recyclerview having number of cards & second the detail screen. As expected

4条回答
  •  无人及你
    2020-12-31 14:46

    I came across this same problem and this how I fixed it.

    When the RecyclerView item is clicked, I pass the current position:

    @Override
    public void onItemClick(View sharedView, String transitionName, int position) {
        viewPosition = position;
        Intent intent = new Intent(this, TransitionActivity.class);
        intent.putExtra("transition", transitionName);
        ActivityOptionsCompat options = ActivityOptionsCompat.
                makeSceneTransitionAnimation(this, sharedView, transitionName);
        ActivityCompat.startActivity(this, intent, options.toBundle());
    }
    

    I save it in onSaveInstanceState to persist across configuration changes:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(VIEW_POSITION, viewPosition);
    }
    

    Then, in the onCreate method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Workaround for orientation change issue
        if (savedInstanceState != null) {
            viewPosition = savedInstanceState.getInt(VIEW_POSITION);
        }
    
        setExitSharedElementCallback(new SharedElementCallback() {
            @Override
            public void onMapSharedElements(List names, Map sharedElements) {
                super.onMapSharedElements(names, sharedElements);
                if (sharedElements.isEmpty()) {
                    View view = recyclerView.getLayoutManager().findViewByPosition(viewPosition);
                    if (view != null) {
                        sharedElements.put(names.get(0), view);
                    }
                }
            }
        });
    }
    

    Cause of the problem: the sharedElements map was empty (I don't know why) after the orientation change.

提交回复
热议问题