Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the addSharedElement api that was added to FragmentTransaction work?

Api 21 has added an api called addSharedElement that looks like it is supposed to be used similar to shared views with activity transitions, see: http://developer.android.com/reference/android/app/FragmentTransaction.html#addSharedElement(android.view.View, java.lang.String))

I attempted to use this api by setting android:transitionName on a view in both fragments and then calling addSharedElement on the FragmentTransaction. On the fragment, I called setSharedElementEnterTransition(new ChangeImageTransform());.

However, this has no effect.

I am running this on the Lollipop preview that was released earlier this month.

like image 360
Spencer Avatar asked Oct 30 '14 00:10

Spencer


People also ask

How do I know if a fragment is already added?

You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.

How do you transition between fragments?

At a high level, here's how to make a fragment transition with shared elements: Assign a unique transition name to each shared element view. Add shared element views and transition names to the FragmentTransaction . Set a shared element transition animation.

What is FragmentTransaction in android?

At runtime, a FragmentManager can add, remove, replace, and perform other actions with fragments in response to user interaction. Each set of fragment changes that you commit is called a transaction, and you can specify what to do inside the transaction using the APIs provided by the FragmentTransaction class.

What is a fragment manager?

FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.


1 Answers

The api addSharedElement(view, name) will match the View view in the exiting Fragment (it can have any non-null transitionName) with a View in the entering Fragment with the transitionName name. This allows you to have different transitionNames from the leaving Fragment and the entering Fragment.

This is a common use case when you have several Views that can be shared elements in a Fragment. For example, a list of images on your device. When you click on one, it replaces the Fragment with a new one that has a detailed View or single image View. The list will give each image a transitionName unique to the item. This could be the row id or content URI, for example. In the single-image view, the transitionName could be constant. Let's say it is "largeImage." You could match them up easily:

fragmentTransaction.addSharedElement(imageIcon, "largeImage");
like image 155
George Mount Avatar answered Sep 30 '22 10:09

George Mount