从我可以告诉(如果我错了,纠正我),你想要实现的基本是这样的:假设你有一个MainActivity,一个DetailsActivity和一组任意图像。 MainActivity显示网格中的图像集,并且DetailsActivity在水平ViewPager中显示相同的图像集。当用户选择MainActivity中的图像时,该图像应该从其在网格中的位置转换到第二个活动的ViewPager中的正确页面。
我们想要解决的问题是“如果用户在”DetailsActivity“中切换页面怎么办?如果发生这种情况,我们要更改在返回转换期间将使用的共享映像。默认情况下,活动转换框架将使用在输入转换期间使用的共享元素…但是查看页面的页面已经改变,所以显然我们想以某种方式覆盖此行为。为此,我们需要在MainActivity和DetailsActivity的onCreate()方法中设置一个SharedElementCallback,并覆盖onMapSharedElements()方法,如下所示:
private final SharedElementCallback mCallback = new SharedElementCallback() {
@Override
public void onMapSharedElements(List names, Map sharedElements) {
if (mCurrentImagePosition != mOriginalImagePosition) {
View sharedView = getImageAtPosition(mCurrentImagePosition);
names.clear();
sharedElements.clear();
names.add(sharedView.getTransitionName());
sharedElements.put(sharedView.getTransitionName(), sharedView);
}
}
/**
* Returns the image of interest to be used as the entering/returning
* shared element during the activity transition.
*/
private View getImageAtPosition(int position) {
// ...
}
};
为了获得更完整的解决方案,我创建了一个可以实现这一效果的sample project on GitHub(在一个StackOverflow应用中有太多的代码发布)。