Hamidreza Shokouhi
Hamidreza Shokouhi

Reputation: 1031

How to implement fragment shared element for pre Lollipop?

I have a recycler view in a fragment that contains an image. I implement OnImageCLickListener that after click on image, a full screen dialog fragment opens and shows the image. now I want to implement shared element transition between my image in recycler view and the full screen dialog of my image in dialog fragment, I also want shared element support pre Lollipop.

How can I do it?

Upvotes: 1

Views: 659

Answers (1)

user6579378
user6579378

Reputation:

At first you have to get the exact position of clicked imageView pass it to the fragment: To get position you can use this:

 int[] location = {0,0};
 mImageView.getLocationOnScreen(location);

and to pass it to your fragment you can use this:

Bundle bundle = new Bundle();
bundle.putInt("locationX",location[0]);
bundle.putInt("locationY",location[1]);

and get it in your fragment by this:

locationX = getArguments().getInt("locationX");
locationY = getArguments().getInt("locationY");

Note: To get that position, dont use methods like view.getTop(), view.getRight(), etc ever. Now you need a simple animation like this in your fragment OnCreateView:

float factor = ((float) (Utils.getWidth(getActivity())) / ((float) (pictureWidth)));

    viewPager.getLayoutParams().height = pictureHeight;
    viewPager.getLayoutParams().width = pictureWidth;
    viewPager.setTranslationY(locationY);
    viewPager.setTranslationX(locationX);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
        viewPager.animate()
                .translationY(Utils.getHeight(getActivity()) / 2 - pictureHeight / 2)
                .scaleX(factor)
                .scaleY(factor)
                .translationX(Utils.getWidth(getActivity()) / 2 - pictureWidth / 2);}

It also supports pre-Lollipop too.

Upvotes: 1

Related Questions