在Transition
中,有1些新的概念,例如Scene
, Transition
, TransitionSet
, TransitionManager
. 除Scene
, 其他的概念其實(shí)和簡單的View動畫差不多。
Scene是1個(gè)新的概念,它被翻譯成了“場景”,這個(gè)描寫很準(zhǔn)確,但是比較難以理解。下面通過源碼分析
/**
* Constructs a Scene which, when entered, will remove any
* children from the sceneRoot container and add the layout
* object as a new child of that container.
*
* @param sceneRoot The root of the hierarchy in which scene changes
* and transitions will take place.
* @param layout The view hierarchy of this scene, added as a child
* of sceneRoot when this scene is entered.
*/
public Scene(ViewGroup sceneRoot, View layout) {
mSceneRoot = sceneRoot;
mLayout = layout;
}
上面是Scene的1個(gè)構(gòu)造器。注釋:構(gòu)造1個(gè)場景,當(dāng)進(jìn)入這個(gè)場景時(shí),將從場景的sceneRoot中移除其他所有的children, 并添加這個(gè)layout作為這個(gè)sceneRoot的新child .
sceneRoot的解釋: 產(chǎn)生場景改變和Transition所在的層次的根 .
layout的解釋:這個(gè)場景指定的view, 當(dāng)進(jìn)入這個(gè)場景時(shí),被添加到sceneRoot的view, 作為sceneRoot的child .
下面是Scene的另外一個(gè)構(gòu)造器
/**
* Constructs a Scene which, when entered, will remove any
* children from the sceneRoot container and will inflate and add
* the hierarchy specified by the layoutId resource file.
*
* <p>This method is hidden because layoutId-based scenes should be
* created by the caching factory method {@link Scene#getCurrentScene(View)}.</p>
*
* @param sceneRoot The root of the hierarchy in which scene changes
* and transitions will take place.
* @param layoutId The id of a resource file that defines the view
* hierarchy of this scene.
* @param context The context used in the process of inflating
* the layout resource.
*/
private Scene(ViewGroup sceneRoot, int layoutId, Context context) {
mContext = context;
mSceneRoot = sceneRoot;
mLayoutId = layoutId;
}
注釋:構(gòu)造1個(gè)場景,當(dāng)進(jìn)入這個(gè)場景時(shí),將從場景的sceneRoot中移除其他所有的children, 并inflate和添加由layoutId指定的資源文件的view層。 這是1個(gè)私有的構(gòu)造器,由于基于layoutId構(gòu)造的場景,使用了緩存,便可以進(jìn)行屢次復(fù)用。
下面是會調(diào)用上面的私有構(gòu)造器的1個(gè)靜態(tài)方法
/**
* Returns a Scene described by the resource file associated with the given
* <code>layoutId</code> parameter. If such a Scene has already been created for
* the given <code>sceneRoot</code>, that same Scene will be returned.
* This caching of layoutId-based scenes enables sharing of common scenes
* between those created in code and those referenced by {@link TransitionManager}
* XML resource files.
*
* @param sceneRoot The root of the hierarchy in which scene changes
* and transitions will take place.
* @param layoutId The id of a standard layout resource file.
* @param context The context used in the process of inflating
* the layout resource.
* @return The scene for the given root and layout id
*/
public static Scene getSceneForLayout(ViewGroup sceneRoot, int layoutId, Context context) {
SparseArray<Scene> scenes = (SparseArray<Scene>) sceneRoot.getTag(
com.android.internal.R.id.scene_layoutid_cache);
if (scenes == null) {
scenes = new SparseArray<Scene>();
sceneRoot.setTagInternal(com.android.internal.R.id.scene_layoutid_cache, scenes);
}
Scene scene = scenes.get(layoutId);
if (scene != null) {
return scene;
} else {
scene = new Scene(sceneRoot, layoutId, context);
scenes.put(layoutId, scene);
return scene;
}
}
注釋:返回1個(gè)由layoutId指定的資源文件描寫的Scene. 如果這個(gè)場景已被sceneRoot創(chuàng)建過了,將返回一樣的場景(復(fù)用). 進(jìn)入layoutId的場景緩存,使得那些在代碼中創(chuàng)建和在xml文件中援用的相同的場景能夠同享(不太明白這為何能夠同享代碼中創(chuàng)建的和在xml文件中描寫的) .
代碼解釋:使用了View.setTag的方式緩存場景列表,當(dāng)需要根據(jù)layoutId創(chuàng)建1個(gè)場景時(shí),如果發(fā)現(xiàn)sceneRoot中已緩存的場景列表中包括了該場景,那末直接返回,否則創(chuàng)建1個(gè)新的場景。
下面是Scene.enter()
方法
/**
* Enters this scene, which entails changing all values that
* are specified by this scene. These may be values associated
* with a layout view group or layout resource file which will
* now be added to the scene root, or it may be values changed by
* an {@link #setEnterAction(Runnable)} enter action}, or a
* combination of the these. No transition will be run when the
* scene is entered. To get transition behavior in scene changes,
* use one of the methods in {@link TransitionManager} instead.
*/
public void enter() {
// Apply layout change, if any
if (mLayoutId > 0 || mLayout != null) {
// empty out parent container before adding to it
getSceneRoot().removeAllViews();
if (mLayoutId > 0) {
LayoutInflater.from(mContext).inflate(mLayoutId, mSceneRoot);
} else {
mSceneRoot.addView(mLayout);
}
}
// Notify next scene that it is entering. Subclasses may override to configure scene.
if (mEnterAction != null) {
mEnterAction.run();
}
setCurrentScene(mSceneRoot, this);
}
從這個(gè)方法中,我們就可以對場景有1個(gè)比較深入的了解了。
注釋:進(jìn)入這個(gè)場景,在這個(gè)場景中需要改變由這個(gè)場景指定的所有values. 這些values可能和將被添加到sceneRoot中的view又換,或是跟被使用setEnterAction(Runnable)
指定的進(jìn)入動作改變。在這個(gè)方法中并沒有使用Transition
, 所以當(dāng)進(jìn)入這個(gè)場景時(shí)不會有Transition觸發(fā)。為了在場景產(chǎn)生改變時(shí)能夠進(jìn)行Transition變換動作,那末應(yīng)當(dāng)使用TransitionManager
方法中的其中1個(gè)。
代碼解釋:當(dāng)在這個(gè)場景中制定了layoutId或是view, 那末則移除sceneRoot中的所有children, 并且添加layoutId指定的view或是view, 最后如果設(shè)置了進(jìn)入的動作,那末調(diào)用該動作。終究的setCurrentScene
方法指定sceneRoot當(dāng)前的場景。
下面是Scene.exit()
方法
/**
* Exits this scene, if it is the current scene
* on the scene's {@link #getSceneRoot() scene root}. The current scene is
* set when {@link #enter() entering} a scene.
* Exiting a scene runs the {@link #setExitAction(Runnable) exit action}
* if there is one.
*/
public void exit() {
if (getCurrentScene(mSceneRoot) == this) {
if (mExitAction != null) {
mExitAction.run();
}
}
}
這個(gè)方法則很簡單,并沒有對sceneRoot的進(jìn)行任何的改變。不清楚會對sceneRoot產(chǎn)生甚么樣的影響。
注釋:如果這個(gè)場景時(shí)sceneRoot確當(dāng)前場景,則退出這個(gè)場景。
簡單分析:Transition是1個(gè)抽象類,保存了兩個(gè)抽象方法由子類實(shí)現(xiàn)captureStartValues(TransitionValues transitionValues)
和captureEndValues(TransitionValues transitionValues)
. 而Transition有1個(gè)常見的子類Visibility
, Android中已有的很多Transition的子類都是繼承自這個(gè)Visibility
.
直接繼承自Transition的類:ChangeBounds, ChangeClipBounds, ChangeImageTransform, ChangeScroll, ChangeTransform, TransitionSet
繼承自Visibility的類:Explode, Fade, Slide
下面是Visibility的注釋
/**
* This transition tracks changes to the visibility of target views in the
* start and end scenes. Visibility is determined not just by the
* {@link View#setVisibility(int)} state of views, but also whether
* views exist in the current view hierarchy. The class is intended to be a
* utility for subclasses such as {@link Fade}, which use this visibility
* information to determine the specific animations to run when visibility
* changes occur. Subclasses should implement one or both of the methods
* {@link #onAppear(ViewGroup, TransitionValues, int, TransitionValues, int)},
* {@link #onDisappear(ViewGroup, TransitionValues, int, TransitionValues, int)} or
* {@link #onAppear(ViewGroup, View, TransitionValues, TransitionValues)},
* {@link #onDisappear(ViewGroup, View, TransitionValues, TransitionValues)}.
*/
public abstract class Visibility extends Transition {
// 省略...
}
注釋:這個(gè)transition跟蹤目標(biāo)view在場景開始和場景結(jié)束時(shí)visibility的變化。Visibility不單單是決定view的visibility狀態(tài), 也決定了view是不是存在在當(dāng)前sceneRoot的view層次中。使用這個(gè)類想為其子類作為1個(gè)工具,例如Fade
這類,使用view的visibility信息來決定當(dāng)visibility產(chǎn)生變化時(shí)特定動畫的運(yùn)行。子類應(yīng)當(dāng)實(shí)現(xiàn)其中1個(gè)或成組的兩個(gè)方法{@link #onAppear(ViewGroup, TransitionValues, int, TransitionValues, int)}
, {@link #onDisappear(ViewGroup, TransitionValues, int, TransitionValues, int)}
或{@link #onAppear(ViewGroup, View, TransitionValues, TransitionValues)}
,{@link #onDisappear(ViewGroup, View, TransitionValues, TransitionValues)}
.
下面是Transition的注釋
/**
* A Transition holds information about animations that will be run on its
* targets during a scene change. Subclasses of this abstract class may
* choreograph several child transitions ({@link TransitionSet} or they may
* perform custom animations themselves. Any Transition has two main jobs:
* (1) capture property values, and (2) play animations based on changes to
* captured property values. A custom transition knows what property values
* on View objects are of interest to it, and also knows how to animate
* changes to those values. For example, the {@link Fade} transition tracks
* changes to visibility-related properties and is able to construct and run
* animations that fade items in or out based on changes to those properties.
*
* <p>Note: Transitions may not work correctly with either {@link SurfaceView}
* or {@link TextureView}, due to the way that these views are displayed
* on the screen. For SurfaceView, the problem is that the view is updated from
* a non-UI thread, so changes to the view due to transitions (such as moving
* and resizing the view) may be out of sync with the display inside those bounds.
* TextureView is more compatible with transitions in general, but some
* specific transitions (such as {@link Fade}) may not be compatible
* with TextureView because they rely on {@link ViewOverlay} functionality,
* which does not currently work with TextureView.</p>
*
* <p>Transitions can be declared in XML resource files inside the <code>res/transition</code>
* directory. Transition resources consist of a tag name for one of the Transition
* subclasses along with attributes to define some of the attributes of that transition.
* For example, here is a minimal resource file that declares a {@link ChangeBounds} transition:
*
* {@sample development/samples/ApiDemos/res/transition/changebounds.xml ChangeBounds}
*
* <p>This TransitionSet contains {@link android.transition.Explode} for visibility,
* {@link android.transition.ChangeBounds}, {@link android.transition.ChangeTransform},
* and {@link android.transition.ChangeClipBounds} and
* {@link android.transition.ChangeImageTransform}:</p>
*
* {@sample development/samples/ApiDemos/res/transition/explode_move_together.xml MultipleTransform}
*
* <p>Custom transition classes may be instantiated with a <code>transition</code> tag:</p>
* <pre><transition class="my.app.transition.CustomTransition"/></pre>
* <p>Custom transition classes loaded from XML should have a public constructor taking
* a {@link android.content.Context} and {@link android.util.AttributeSet}.</p>
*
* <p>Note that attributes for the transition are not required, just as they are
* optional when declared in code; Transitions created from XML resources will use
* the same defaults as their code-created equivalents. Here is a slightly more
* elaborate example which declares a {@link TransitionSet} transition with
* {@link ChangeBounds} and {@link Fade} child transitions:</p>
*
* {@sample
* development/samples/ApiDemos/res/transition/changebounds_fadeout_sequential.xml TransitionSet}
*
* <p>In this example, the transitionOrdering attribute is used on the TransitionSet
* object to change from the default {@link TransitionSet#ORDERING_TOGETHER} behavior
* to be {@link TransitionSet#ORDERING_SEQUENTIAL} instead. Also, the {@link Fade}
* transition uses a fadingMode of {@link Fade#OUT} instead of the default
* out-in behavior. Finally, note the use of the <code>targets</code> sub-tag, which
* takes a set of {@link android.R.styleable#TransitionTarget target} tags, each
* of which lists a specific <code>targetId</code>, <code>targetClass</code>,
* <code>targetName</code>, <code>excludeId</code>, <code>excludeClass</code>, or
* <code>excludeName</code>, which this transition acts upon.
* Use of targets is optional, but can be used to either limit the time spent checking
* attributes on unchanging views, or limiting the types of animations run on specific views.
* In this case, we know that only the <code>grayscaleContainer</code> will be
* disappearing, so we choose to limit the {@link Fade} transition to only that view.</p>
*
* Further information on XML resource descriptions for transitions can be found for
* {@link android.R.styleable#Transition}, {@link android.R.styleable#TransitionSet},
* {@link android.R.styleable#TransitionTarget}, {@link android.R.styleable#Fade},
* {@link android.R.styleable#Slide}, and {@link android.R.styleable#ChangeTransform}.
*
*/
public abstract class Transition implements Cloneable {
// 省略...
}
注釋翻譯:1個(gè)Transition具有在它的目標(biāo)view在場景切換時(shí)進(jìn)行的動畫的信息。這個(gè)類的子類可使用TransitionSet組合多個(gè)子Transition, 或他們也能夠進(jìn)行自定義的動畫。所有的Transition有兩個(gè)主要的工作,1是捕獲屬性信息,2是基于屬性信息的改變進(jìn)行動畫。1個(gè)自定義的Transition知道目標(biāo)view它所關(guān)心的信息,也知道如果將這些信息的改變進(jìn)行動畫。例如,F(xiàn)ade跟蹤visibility相干的屬性,而且能夠根據(jù)這些信息構(gòu)造和運(yùn)行動畫,讓這些item進(jìn)行淡入或淡出。
注意:Transition可能不會再SurfaceView或TextureView上正確的履行, 由于這些view的更新不是在主線程…
我們可以在xml中定義Transition. Transition資源中以Transition子類的名字作為tag, 并且可以添加1些attributes作為Transition的屬性。
目前還不清楚TransitionManager的具體管理Transition的方式是甚么。就使用而言,除可以在代碼中直接構(gòu)造,還可以通過在xml中定義的方式來獲得。
// transition-v21/manager
<transitionManager xmlns:android="http://schemas.android.com/apk/res/android">
<transition
android:fromScene="@layout/card_one"
android:toScene="@layout/card_two"
android:transition="@transition/decrease"/>
<transition
android:fromScene="@layout/card_two"
android:toScene="@layout/card_one"
android:transition="@android:transition/move"/>
</transitionManager>
// transition-v21/descrease
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
<fade android:fadingMode="fade_out">
<targets android:targetId="@id/red"/>
</fade>
<fade android:fadingMode="fade_out">
<targets android:targetId="@id/blue"/>
</fade>
<changeBounds>
<targets android:targetId="@id/green"/>
</changeBounds>
<changeBounds>
<targets android:targetId="@id/yellow"/>
</changeBounds>
</transitionSet>
// layout/card_one
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/red"
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@android:color/holo_red_light"/>
<TextView
android:id="@+id/blue"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_toEndOf="@id/red"
android:background="@android:color/holo_blue_bright"/>
<TextView
android:id="@+id/green"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_below="@id/red"
android:background="@android:color/holo_green_light"/>
<TextView
android:id="@+id/yellow"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignTop="@id/green"
android:layout_toEndOf="@id/green"
android:background="@android:color/holo_orange_light"/>
</RelativeLayout>
// layout/card_two
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/green"
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@android:color/holo_green_light"/>
<TextView
android:id="@+id/yellow"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignTop="@id/green"
android:layout_toEndOf="@id/green"
android:background="@android:color/holo_orange_light"/>
</RelativeLayout>
如上,在xml中定義1個(gè)TransitionManager, 在transitionManager中可以定義多個(gè)transition .
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
TransitionManager transitionManager = TransitionInflater.from(this).inflateTransitionManager(R.transition.manger, mContainer);
if (isFirst) {
isFirst = false;
transitionManager.transitionTo(Scene.getSceneForLayout(mContainer, R.layout.card_one, this));
} else {
isFirst = true;
transitionManager.transitionTo(Scene.getSceneForLayout(mContainer, R.layout.card_two, this));
}
}
如上,在代碼中inflate出在xml中定義的TransitionManager, 然落后行動畫。
這里可以看1下TransitionInflater.inflateTransitionManager
方法進(jìn)行inflate的進(jìn)程
private TransitionManager createTransitionManagerFromXml(XmlPullParser parser,
AttributeSet attrs, ViewGroup sceneRoot) throws XmlPullParserException, IOException {
// Make sure we are on a start tag.
int type;
int depth = parser.getDepth();
TransitionManager transitionManager = null;
while (((type=parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("transitionManager")) {
transitionManager = new TransitionManager();
} else if (name.equals("transition") && (transitionManager != null)) {
loadTransition(attrs, sceneRoot, transitionManager);
} else {
throw new RuntimeException("Unknown scene name: " + parser.getName());
}
}
return transitionManager;
}
private void loadTransition(AttributeSet attrs, ViewGroup sceneRoot,
TransitionManager transitionManager) throws Resources.NotFoundException {
TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.TransitionManager);
int transitionId = a.getResourceId(R.styleable.TransitionManager_transition, -1);
int fromId = a.getResourceId(R.styleable.TransitionManager_fromScene, -1);
Scene fromScene = (fromId < 0) ? null: Scene.getSceneForLayout(sceneRoot, fromId, mContext);
int toId = a.getResourceId(R.styleable.TransitionManager_toScene, -1);
Scene toScene = (toId < 0) ? null : Scene.getSceneForLayout(sceneRoot, toId, mContext);
if (transitionId >= 0) {
Transition transition = inflateTransition(transitionId);
if (transition != null) {
if (toScene == null) {
throw new RuntimeException("No toScene for transition ID " + transitionId);
}
if (fromScene == null) {
transitionManager.setTransition(toScene, transition);
} else {
transitionManager.setTransition(fromScene, toScene, transition);
}
}
}
a.recycle();
}
分析:在inflate TransitionManager的進(jìn)程中,實(shí)際上是直接構(gòu)造TransitionManger的。對其中的transition標(biāo)簽進(jìn)行處理,也是調(diào)用TransitionManager.setTransition(Scene, Scene, Transiton)
方法。這個(gè)方法有1個(gè)重載方法。在上面可以看到,toScene是必須存在的,如果fromScene存在,則調(diào)用TransitionManager.setTransition(Scene, Scene, Transiton)
, 否則調(diào)用TransitionManager.setTransition(Scene, Transiton)
.
我們可以從中看到甚么呢?這個(gè)需要從TransitionManager.transitionTo(Scene)
中看出來
/**
* Change to the given scene, using the
* appropriate transition for this particular scene change
* (as specified to the TransitionManager, or the default
* if no such transition exists).
*
* @param scene The Scene to change to
*/
public void transitionTo(Scene scene) {
// Auto transition if there is no transition declared for the Scene, but there is
// a root or parent view
changeScene(scene, getTransition(scene));
}
注釋翻譯:變換到給定的場景,使用為這個(gè)場景變換指定的適合的Transition. (如果已在TransitionManger中設(shè)置了, 或使用默許的).
這里需要側(cè)重看括號中的部份,從其中我們可以猜到,實(shí)際上,調(diào)用TransitionManager.setTransition(
就是為Scene變換設(shè)置1個(gè)Transition, 如果我們之前scene設(shè)置了1個(gè)Transition, 那末我們使用的是我們設(shè)置的Transition, 否則就是使用默許的AutoTransition. 其實(shí),將setTransition改成putTransition更加適合。
很大1部份動畫其實(shí)都可使用這個(gè)方法來進(jìn)行動畫。這個(gè)方法有1個(gè)重載方法TransitionManager.beginDelayedTransition(ViewGroup sceneRoot)
, 在這個(gè)重載方法中,使用1個(gè)默許的AutoTransition.
public void transition(View view) {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
final ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
final ViewGroup container = (ViewGroup) findViewById(R.id.container);
TransitionManager.beginDelayedTransition(parent, new ChangeBounds());
container.removeViewAt(0);
container.removeViewAt(0);
}
如上,有1個(gè)id為parent的ViewGroup, 其中有1個(gè)id為container的ViewGroup, 在container中,還有多個(gè)children, 我們以id為parent的ViewGroup作為sceneRoot, 在改變其hirerarchy前調(diào)用TransitionManager.beginDelayedTransition(ViewGroup sceneRoot, Transition transition)
, 然后對其hirerarchy進(jìn)行操作, 這樣就完成了動畫的操作。
這里需要說明1下,我們以id為parent的ViewGroup作為sceneRoot, 而操作的其實(shí)不是它的直接children, 也產(chǎn)生了效果,說明操作的是以sceneRoot為根的全部hirerarchy.
對原理,這里暫時(shí)放在后面進(jìn)行分析。
在這個(gè)方法中使用到了Scene的概念,固然上面的方法也使用到了Scene的概念,只是在方法上并沒有暴露。對Scene, 我們在上面已分析了,進(jìn)行場景切換時(shí),是將sceneRoot中原來的所有的children移除,然后添加在Scene中指定的view.
這個(gè)方法也有1個(gè)重載方法TransitionManager.go(Scene)
, 其中也會使用默許的AutoTransition
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void remove(View view) {
final ViewGroup group = (ViewGroup) findViewById(R.id.container);
final Scene scene = new Scene(group, group.getChildAt(0));
TransitionManager.go(scene);
}
如上所示,我們將1個(gè)id為container的ViewGroup作為sceneRoot, 然后將其第1個(gè)child作為場景切換后添加到sceneRoot中的view, 然后調(diào)用TransitionManager.go(Scene)方法。固然,這樣到達(dá)的效果和使用
TransitionManager.beginDelayedTransition(ViewGroup sceneRoot, Transition transition)的效果是1樣的。我們也能夠像上面1樣使用,保存id為container的第1個(gè)child, 移除其他所有的children, 在這些操作之前調(diào)用
TransitionManager.beginDelayedTransition(ViewGroup sceneRoot, Transition transition)“`方法便可。
在上面我們已演示了這個(gè)方法的使用。這里就不再贅述。
在這里,其實(shí)已對Transition框架的使用做了完全的分析,能夠處理大部份的動畫。Transition的使用也就只有上面3種方式。
如果需要自定義Transition, 那末就需要對Transition的實(shí)現(xiàn)進(jìn)行分析了,這里暫時(shí)不做分析。
使用 Transition API為安卓利用創(chuàng)建動畫