建立自訂的轉場動畫
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
試試 Compose 的方式
Jetpack Compose 是 Android 推薦的 UI 工具包。瞭解如何在 Compose 中新增動畫。
您可以使用自訂轉場建立任何內建轉場類別都無法提供的動畫。舉例來說,您可以定義自訂轉場效果,將文字和輸入欄位的前景色設為灰色,以表示新畫面中已停用這些欄位。這類變更可讓使用者查看您停用的欄位。
自訂轉場效果 (例如內建轉場效果類型之一) 會將動畫套用至起始和結束場景的子檢視畫面。不過,與內建轉場類型不同,您必須提供用於擷取屬性值並產生動畫的程式碼。您也可以為動畫定義目標檢視畫面的子集。
本頁面將說明如何擷取資源值並產生動畫,以建立自訂轉場效果。
擴充 Transition 類別
如要建立自訂轉場效果,請在專案中新增可擴充 Transition
類別的類別,並覆寫下列程式碼片段中顯示的函式:
Kotlin
class CustomTransition : Transition() {
override fun captureStartValues(transitionValues: TransitionValues) {}
override fun captureEndValues(transitionValues: TransitionValues) {}
override fun createAnimator(
sceneRoot: ViewGroup,
startValues: TransitionValues?,
endValues: TransitionValues?
): Animator? {}
}
Java
public class CustomTransition extends Transition {
@Override
public void captureStartValues(TransitionValues values) {}
@Override
public void captureEndValues(TransitionValues values) {}
@Override
public Animator createAnimator(ViewGroup sceneRoot,
TransitionValues startValues,
TransitionValues endValues) {}
}
以下各節將說明如何覆寫這些函式。
擷取檢視畫面屬性值
轉場動畫會使用「屬性動畫總覽」一文中所述的屬性動畫系統。屬性動畫會在指定時間範圍內,將檢視畫面屬性從開始值變更為結束值,因此架構需要同時具備屬性的開始值和結束值,才能建構動畫。
不過,屬性動畫通常只需要所有檢視畫面屬性值的一小部分。舉例來說,顏色動畫需要顏色屬性值,而移動動畫則需要位置屬性值。由於動畫所需的屬性值與轉場相關,轉場架構並不會將每個屬性值都提供給轉場。相反地,架構會叫用回呼函式,讓轉場只擷取所需的屬性值,並將這些值儲存在架構中。
擷取起始值
如要將起始檢視畫面值傳遞至架構,請實作 captureStartValues(transitionValues)
函式。架構會針對起始場景中的每個檢視畫面呼叫此函式。函式引數是 TransitionValues
物件,其中包含對檢視畫面的參照,以及可用於儲存所需檢視畫面值的 Map
例項。在實作中,請擷取這些屬性值,並將這些值儲存在地圖中,再傳回至架構。
為確保屬性值的鍵不會與其他 TransitionValues
鍵衝突,請使用下列命名慣例:
package_name:transition_name:property_name
以下程式碼片段顯示 captureStartValues()
函式的實作方式:
Kotlin
class CustomTransition : Transition() {
// Define a key for storing a property value in
// TransitionValues.values with the syntax
// package_name:transition_class:property_name to avoid collisions
private val PROPNAME_BACKGROUND = "com.example.android.customtransition:CustomTransition:background"
override fun captureStartValues(transitionValues: TransitionValues) {
// Call the convenience method captureValues
captureValues(transitionValues)
}
// For the view in transitionValues.view, get the values you
// want and put them in transitionValues.values
private fun captureValues(transitionValues: TransitionValues) {
// Get a reference to the view
val view = transitionValues.view
// Store its background property in the values map
transitionValues.values[PROPNAME_BACKGROUND] = view.background
}
...
}
Java
public class CustomTransition extends Transition {
// Define a key for storing a property value in
// TransitionValues.values with the syntax
// package_name:transition_class:property_name to avoid collisions
private static final String PROPNAME_BACKGROUND =
"com.example.android.customtransition:CustomTransition:background";
@Override
public void captureStartValues(TransitionValues transitionValues) {
// Call the convenience method captureValues
captureValues(transitionValues);
}
// For the view in transitionValues.view, get the values you
// want and put them in transitionValues.values
private void captureValues(TransitionValues transitionValues) {
// Get a reference to the view
View view = transitionValues.view;
// Store its background property in the values map
transitionValues.values.put(PROPNAME_BACKGROUND, view.getBackground());
}
...
}
擷取結束值
架構會針對結束場景中的每個目標檢視畫面呼叫 captureEndValues(TransitionValues)
函式一次。在其他方面,captureEndValues()
的運作方式與 captureStartValues()
相同。
下列程式碼片段顯示 captureEndValues()
函式的實作方式:
Kotlin
override fun captureEndValues(transitionValues: TransitionValues) {
captureValues(transitionValues)
}
Java
@Override
public void captureEndValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
在這個範例中,captureStartValues()
和 captureEndValues()
函式都會叫用 captureValues()
來擷取及儲存值。captureValues()
擷取的檢視畫面屬性相同,但在起始和結束場景中具有不同的值。此架構會為檢視畫面的開始和結束狀態維護個別對應表。
建立自訂動畫器
如要為檢視畫面在起始場景和結束場景之間的狀態變更設定動畫,請覆寫 createAnimator()
函式,提供動畫片段。當架構呼叫此函式時,會傳入場景根目錄檢視畫面,以及包含您擷取的開始和結束值的 TransitionValues
物件。
架構呼叫 createAnimator()
函式的次數取決於起始場景和結束場景之間發生的變更。
舉例來說,假設淡出或淡入動畫是以自訂轉場實作,如果起始場景有五個目標,其中兩個目標會從結束場景移除,而結束場景則有起始場景的三個目標加上一個新目標,則架構會呼叫 createAnimator()
六次。其中三個呼叫會為停留在兩個場景物件中的目標製作淡出和淡入動畫。另外兩個呼叫會為從結尾場景移除的目標提供淡出動畫。一個呼叫會在結束場景中,為新目標提供淡入動畫效果。
如果目標檢視畫面同時出現在起始和結束場景中,架構會為 startValues
和 endValues
引數提供 TransitionValues
物件。如果目標檢視畫面只存在於起始或結束場景中,架構會為對應的引數提供 TransitionValues
物件,並為其他引數提供 null
。
如要在建立自訂轉場效果時導入 createAnimator(ViewGroup, TransitionValues, TransitionValues)
函式,請使用您擷取的檢視畫面屬性值,建立 Animator
物件並傳回至架構。如需實作範例,請參閱「
CustomTransition」範例中的 ChangeColor
類別。如要進一步瞭解屬性動畫器,請參閱「屬性動畫」。
套用自訂轉場效果
自訂轉場效果的運作方式與內建轉場效果相同。您可以使用轉場管理員套用自訂轉場效果,如「套用轉場效果」一節所述。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-24 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-24 (世界標準時間)。"],[],[],null,["# Create a custom transition animation\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to add animations in Compose. \n[Add multiple properties with a transition in Compose →](/develop/ui/compose/animation/value-based#updateTransition) \n\nA custom transition lets you create an animation that is not available from any of\nthe built-in transition classes. For example, you can define a custom transition that turns\nthe foreground color of text and input fields to gray to indicate that the fields are disabled\nin the new screen. This type of change helps users see the fields you disabled.\n\nA custom transition, like one of the built-in transition types, applies animations to\nchild views of both the starting and ending scenes. However, unlike built-in transition types,\nyou have to provide the code that captures property values and generates animations.\nYou might also want to define a subset of target views for your animation.\n\nThis page teaches you how to capture property values and generate animations to create\ncustom transitions.\n\nExtend the Transition class\n---------------------------\n\nTo create a custom transition, add a class to your project that extends the [Transition](/reference/android/transition/Transition) class and override the functions shown in the following snippet: \n\n### Kotlin\n\n```kotlin\nclass CustomTransition : Transition() {\n\n override fun captureStartValues(transitionValues: TransitionValues) {}\n\n override fun captureEndValues(transitionValues: TransitionValues) {}\n\n override fun createAnimator(\n sceneRoot: ViewGroup,\n startValues: TransitionValues?,\n endValues: TransitionValues?\n ): Animator? {}\n\n}\n```\n\n### Java\n\n```java\npublic class CustomTransition extends Transition {\n\n @Override\n public void captureStartValues(TransitionValues values) {}\n\n @Override\n public void captureEndValues(TransitionValues values) {}\n\n @Override\n public Animator createAnimator(ViewGroup sceneRoot,\n TransitionValues startValues,\n TransitionValues endValues) {}\n}\n```\n\nThe following sections explain how to override these functions.\n\nCapture view property values\n----------------------------\n\nTransition animations use the property animation system described in\n[Property animation overview](/guide/topics/graphics/prop-animation). Property\nanimations change a view property from a starting value to an ending value over a specified\nperiod of time, so the framework needs to have both the starting and ending values of\nthe property to construct the animation.\n\nHowever, a property animation usually needs only a small subset of all the view's property\nvalues. For example, a color animation needs color property values, while a movement\nanimation needs position property values. Since the property values needed for an animation\nare specific to a transition, the transitions framework does not provide every property value\nto a transition. Instead, the framework invokes callback functions that allow a transition to\ncapture only the property values it needs and store them in the framework.\n\n### Capture starting values\n\nTo pass the starting view values to the framework, implement the\n[captureStartValues(transitionValues)](/reference/android/transition/Transition#captureStartValues(android.transition.TransitionValues))\nfunction. The framework calls this function for every view in the starting scene. The function\nargument is a [TransitionValues](/reference/android/transition/TransitionValues) object that contains a reference\nto the view and a [Map](/reference/java/util/Map) instance in which you can store the view values you\nwant. In your implementation, retrieve these property values and pass them back to the\nframework by storing them in the map.\n\nTo ensure that the key for a property value does not conflict with other\n`TransitionValues` keys, use the following naming scheme: \n\n```xml\npackage_name:transition_name:property_name\n```\n\nThe following snippet shows an implementation of the `captureStartValues()` function: \n\n### Kotlin\n\n```kotlin\nclass CustomTransition : Transition() {\n\n // Define a key for storing a property value in\n // TransitionValues.values with the syntax\n // package_name:transition_class:property_name to avoid collisions\n private val PROPNAME_BACKGROUND = \"com.example.android.customtransition:CustomTransition:background\"\n\n override fun captureStartValues(transitionValues: TransitionValues) {\n // Call the convenience method captureValues\n captureValues(transitionValues)\n }\n\n // For the view in transitionValues.view, get the values you\n // want and put them in transitionValues.values\n private fun captureValues(transitionValues: TransitionValues) {\n // Get a reference to the view\n val view = transitionValues.view\n // Store its background property in the values map\n transitionValues.values[PROPNAME_BACKGROUND] = view.background\n }\n\n ...\n\n}\n```\n\n### Java\n\n```java\npublic class CustomTransition extends Transition {\n\n // Define a key for storing a property value in\n // TransitionValues.values with the syntax\n // package_name:transition_class:property_name to avoid collisions\n private static final String PROPNAME_BACKGROUND =\n \"com.example.android.customtransition:CustomTransition:background\";\n\n @Override\n public void captureStartValues(TransitionValues transitionValues) {\n // Call the convenience method captureValues\n captureValues(transitionValues);\n }\n\n\n // For the view in transitionValues.view, get the values you\n // want and put them in transitionValues.values\n private void captureValues(TransitionValues transitionValues) {\n // Get a reference to the view\n View view = transitionValues.view;\n // Store its background property in the values map\n transitionValues.values.put(PROPNAME_BACKGROUND, view.getBackground());\n }\n ...\n}\n```\n\n### Capture ending values\n\nThe framework calls the [captureEndValues(TransitionValues)](/reference/android/transition/Transition#captureEndValues(android.transition.TransitionValues)) function\nonce for every target view in the ending scene. In all other respects, `captureEndValues()` works the same as `captureStartValues()`.\n\nThe following code snippet shows an implementation of the `captureEndValues()` function: \n\n### Kotlin\n\n```kotlin\noverride fun captureEndValues(transitionValues: TransitionValues) {\n captureValues(transitionValues)\n}\n```\n\n### Java\n\n```java\n@Override\npublic void captureEndValues(TransitionValues transitionValues) {\n captureValues(transitionValues);\n}\n```\n\nIn this example, both the `captureStartValues()` and `captureEndValues()`\nfunctions invoke `captureValues()` to retrieve and store values. The view property\nthat `captureValues()` retrieves is the same, but it has different values in the\nstarting and ending scenes. The framework maintains separate maps for the starting and ending\nstates of a view.\n\nCreate a custom animator\n------------------------\n\nTo animate the changes to a view between its state in the starting scene and its state in\nthe ending scene, provide an animator by overriding the\n[createAnimator()](/reference/android/transition/Transition#createAnimator(android.view.ViewGroup, android.transition.TransitionValues, android.transition.TransitionValues))\nfunction. When the framework calls this function, it passes in the scene root view and the\n`TransitionValues` objects that contain the starting and ending values\nyou captured.\n\nThe number of times the framework calls the `createAnimator()` function depends on the\nchanges that occur between the starting and ending scenes.\n\nFor example, consider a fade-out or\nfade-in animation implemented as a custom transition. If the starting scene has five targets, of\nwhich two are removed from the ending scene, and the ending scene has the three targets from the\nstarting scene plus a new target, then the framework calls `createAnimator()` six times.\nThree of the calls animate the fade-out and fade-in of the targets that stay in both scene\nobjects. Two more calls animate the fade-out of the targets removed from the ending scene. One\ncall animates the fade-in of the new target in the ending scene.\n\nFor target views that exist in both the starting and ending scenes, the framework provides\na `TransitionValues` object for both the `startValues` and\n`endValues` arguments. For target views that only exist in the starting or the\nending scene, the framework provides a `TransitionValues` object\nfor the corresponding argument and `null` for the other.\n\nTo implement the [createAnimator(ViewGroup, TransitionValues, TransitionValues)](/reference/android/transition/Transition#createAnimator(android.view.ViewGroup, android.transition.TransitionValues, android.transition.TransitionValues)) function when you create\na custom transition, use the view property values you captured to create an [Animator](/reference/android/animation/Animator) object and return it to the framework. For an example implementation,\nsee the [ChangeColor](https://github.com/android/animation-samples/blob/master/CustomTransition/Application/src/main/java/com/example/android/customtransition/ChangeColor.java) class in the [CustomTransition](https://github.com/android/animation-samples/tree/main/CustomTransition) sample. For more information about property animators, see\n[Property animation](/guide/topics/graphics/prop-animation).\n\nApply a custom transition\n-------------------------\n\nCustom transitions work the same as built-in transitions. You can apply a custom transition\nusing a transition manager, as described in [Apply a transition](/training/transitions/transitions#Apply)."]]