GridView与ViewPager共享元素转换与Fragments / FragmentTransaction

时间:2017-03-24 23:22:57

标签: android android-fragments gridview android-viewpager shared-element-transition

我有以下视图结构:

  • 一项活动
  • 活动包含一个带有ViewPager的片段和其他一些东西
  • 每个页面都包含一个片段
  • 一页片段包含一个GridView
  • 当点击GridView中的某个项目时,我将顶层片段替换为另一个片段,以全屏显示GridView的图像。这个片段还有一个ViewPager,每个页面都是一个ImageView。

当我点击网格中的一个图像时,我可以显示全屏片段并显示正确的图像。然后,用户可以向左/向右滑动以查看其他图像。

结构如下:

-Activity
--MasterFragment
---ViewPager
----GalleryFragment
-----GridView
------ImageView

在FragmentTransaction中替换片段后,它看起来像:

-Activity
--GalleryFullscreenFragment
---ViewPager
----ImageView

从我的GalleryFragment中,我使用以下代码显示我的全屏图库:

 GalleryFullscreenFragment fragment = new GalleryFullscreenFragment();
 Bundle args = new Bundle();
 args.putStringArrayList(ARG_IMAGES, images); //ArrayList<String> containing urls
 args.putInt(ARG_POSITION, position); //Selected image position
 fragment.setArguments(args);

 getActivity().getSupportFragmentManager()
             .beginTransaction()
             .replace(R.id.drawer_content, fragment)
             .addToBackStack(null)
             .commit();

我现在想要通过从GalleryFragment中的GridView中的选定ImageView过渡到GalleryFullscreenFragment中ViewPager中的ImageView来实现共享元素过渡。

我尝试通过xml实现transitionName属性,但根本不起作用。相反,我现在使用我的适配器类在imageviews上设置适当的transitionName:

//ArrayAdapter in GalleryFragment used for GridView
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    ...
    imageView.setTransitionName("image" + position);
    ...
}

//PagerAdapter in FullscreenGalleryFragment used for ViewPager
public Object instantiateItem(ViewGroup container, int position) { 
    ...
    imageView.setTransitionName("image"+position);
    ...
}

最后在提交FragmentTransaction之前,我将共享元素设置为

ImageView image = (ImageView) view.findViewById(R.id.image_view);
... //Setup the transaction
transaction.addSharedElement(image, image.getTransitionName());
transaction.commit;

现在真的很奇怪了。有时,转换只是按照您的预期运行。有时它根本不起作用,有时候除了它们应该在哪里之外,所有地方的观点都会结束。

经过一番研究后,我想我找到了原因。从我可以说的问题是,转换发生时适配器有时没有准备好(不确定我是否正确理解)。所以有时候动画搞砸了。

接下来,我正在使用Picasso库将图像加载到图像视图中。

最大的问题是:如何正确设置图片视图动画,以便我获得一个不错的共享元素转换?

0 个答案:

没有答案