Azurlake Azurlake - 14 days ago 9
Android Question

Android - Different transitions with multiple shared elements

I'm working with Android Lollipop Transitions, and I've sumbled upon the following problem:


  1. I have
    CardView
    with an
    ImageView
    and, on top of it, a
    TextView
    .

  2. When I click on the card, a new Activity is launched, and it contains both the
    ImageView
    and the
    TextView
    in different positions.

  3. If I don't include the
    TextView
    in the
    Transition
    as a shared element, it suddenly dissapears [goes behind] the
    ImageView
    , which doesn't look, well, great.

  4. If I include it, it doesn't scale the text nicely and suddenly changes to the final size (I am aware of this solution already, but the problem is I want to keep also the default
    ImageView
    Transition
    , which is a combination of a
    ChangeBounds
    Transition
    , a
    ChangeImageTransform
    , ... among others).



So, anybody knows how to have different transitions being thrown for different shared views when launching the new
Activity
?

Cheers

Answer

OK,

This is achievable extending the Transition class. Since I wanted to animate differently an ImageView and a TextView, I just wrote a TextTransform child class ofTransform, analogous to the ChangeImageTransform one which is part of the Android API 21+. The key was overriding this method (shown the case for ChangeImageTransform which looks for ImageView objects):

@Override
private void captureValues(TransitionValues transitionValues) {
    View view = transitionValues.view;
    if (!(view instanceof ImageView) || view.getVisibility() != View.VISIBLE) {
        return;
    }
    (...)
}

Then you apply all transforms to the new scene, and relevant transform will be attached to their corresponding views:

<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <fade android:fadingMode="fade_out" />
    <changeBounds />
    <changeImageTransform />
    <com.mypackage.transforms.TextTransform />
    <fade android:fadingMode="fade_in" />
</transitionSet>

And then you set this Transition on the OnCreate method of the new Activity using setSharedElementEnterTransition(inflatedTransitionSet);

Comments