我遇到了同样的问题,这就是我解决它的方法。
单击 RecyclerView 项时,我通过当前位置:
@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());
}
我将其保存在 onSaveInstanceState 中以在配置更改中保持不变:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(VIEW_POSITION, viewPosition);
}
然后,在 onCreate 方法中:
@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<String> names, Map<String, View> sharedElements) {
super.onMapSharedElements(names, sharedElements);
if (sharedElements.isEmpty()) {
View view = recyclerView.getLayoutManager().findViewByPosition(viewPosition);
if (view != null) {
sharedElements.put(names.get(0), view);
}
}
}
});
}
问题的原因:方向改变后 sharedElements 地图是空的(我不知道为什么)。