Compose 中的共用元素轉換

如果可組合項的內容在可組合項之間保持一致,共用元素轉場效果可以流暢切換。通常用於瀏覽,可讓您在使用者瀏覽不同畫面時,透過視覺化方式連結不同畫面。

舉例來說,在下方影片中,您可以看到點心圖片和標題從清單頁面分享到詳細資料頁面。

圖 1. Jetsnack 共用元素示範

Compose 提供幾個高階 API,可協助您建立共用元素:

  • SharedTransitionLayout:實作共用元素轉場效果所需的邊界版面配置。其提供 SharedTransitionScope。可組合項必須位於 SharedTransitionScope 中,才能使用共用元素修飾符。
  • Modifier.sharedElement():修飾符會將應與其他可組合項比對的可組合項,標記為 SharedTransitionScope
  • Modifier.sharedBounds():修飾符會向 SharedTransitionScope 標示,這個可組合函式的邊界應用於轉場作業的容器邊界。與 sharedElement() 不同,sharedBounds() 是專為視覺上不同的內容而設計。

在 Compose 中建立共用元素時,有一個重要的概念是與疊加層和剪輯搭配使用。如要進一步瞭解這項重要主題,請參閱「裁剪和重疊」一節。

基本用法

本節將建構以下轉換作業,從較小的「清單」項目轉換至較大的詳細項目:

圖 2.兩個可組合項之間的共用元素轉換基本範例。

使用 Modifier.sharedElement() 的最佳方法就是搭配 AnimatedContentAnimatedVisibilityNavHost,系統會自動為您管理可組合項之間的轉換。

起點是具備 MainContentDetailsContent 可組合項的現有基本 AnimatedContent,然後才新增共用元素:

圖 3.在沒有任何共用元素轉換的情況下啟動 AnimatedContent

  1. 如要讓共用元素在兩個版面配置之間建立動畫,請使用 SharedTransitionLayoutAnimatedContent 可組合項包住。從 SharedTransitionLayoutAnimatedContent 傳遞的範圍會傳遞至 MainContentDetailsContent

    var showDetails by remember {
        mutableStateOf(false)
    }
    SharedTransitionLayout {
        AnimatedContent(
            showDetails,
            label = "basic_transition"
        ) { targetState ->
            if (!targetState) {
                MainContent(
                    onShowDetails = {
                        showDetails = true
                    },
                    animatedVisibilityScope = this@AnimatedContent,
                    sharedTransitionScope = this@SharedTransitionLayout
                )
            } else {
                DetailsContent(
                    onBack = {
                        showDetails = false
                    },
                    animatedVisibilityScope = this@AnimatedContent,
                    sharedTransitionScope = this@SharedTransitionLayout
                )
            }
        }
    }

  2. 在兩個相符的可組合項上,將 Modifier.sharedElement() 新增至可組合項修飾符鏈結。建立 SharedContentState 物件,並使用 rememberSharedContentState() 記住該物件。SharedContentState 物件會儲存決定共用元素的專屬索引鍵。請提供可識別內容的專屬鍵,並使用 rememberSharedContentState() 標記要記住的項目。AnimatedContentScope 會傳遞至輔助鍵,用於協調動畫。

    @Composable
    private fun MainContent(
        onShowDetails: () -> Unit,
        modifier: Modifier = Modifier,
        sharedTransitionScope: SharedTransitionScope,
        animatedVisibilityScope: AnimatedVisibilityScope
    ) {
        Row(
            // ...
        ) {
            with(sharedTransitionScope) {
                Image(
                    painter = painterResource(id = R.drawable.cupcake),
                    contentDescription = "Cupcake",
                    modifier = Modifier
                        .sharedElement(
                            rememberSharedContentState(key = "image"),
                            animatedVisibilityScope = animatedVisibilityScope
                        )
                        .size(100.dp)
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                // ...
            }
        }
    }
    
    @Composable
    private fun DetailsContent(
        modifier: Modifier = Modifier,
        onBack: () -> Unit,
        sharedTransitionScope: SharedTransitionScope,
        animatedVisibilityScope: AnimatedVisibilityScope
    ) {
        Column(
            // ...
        ) {
            with(sharedTransitionScope) {
                Image(
                    painter = painterResource(id = R.drawable.cupcake),
                    contentDescription = "Cupcake",
                    modifier = Modifier
                        .sharedElement(
                            rememberSharedContentState(key = "image"),
                            animatedVisibilityScope = animatedVisibilityScope
                        )
                        .size(200.dp)
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                // ...
            }
        }
    }

如要取得共用元素是否相符的資訊,請將 rememberSharedContentState() 擷取至變數,並查詢 isMatchFound

這會產生以下自動動畫:

圖 4.兩個可組合項之間的共用元素轉換基本範例。

您可能會發現,整個容器的背景顏色和大小仍使用預設的 AnimatedContent 設定。

共用邊界與共用元素

Modifier.sharedBounds()Modifier.sharedElement() 類似。不過,修飾符有以下差異:

  • sharedBounds() 適用於視覺上存在差異的內容,但狀態之間應共用相同區域的內容,而 sharedElement() 會預期內容相同。
  • 使用 sharedBounds() 時,進入及離開畫面的內容會在兩個狀態轉換期間顯示,而 sharedElement() 則只會在轉換邊界中轉譯目標內容。Modifier.sharedBounds()enterexit 參數,可用來指定內容的轉場方式,類似於 AnimatedContent 的運作方式。
  • sharedBounds() 最常見的用途是容器轉換模式sharedElement() 範例的用途則是主頁橫幅轉換。
  • 使用 Text 可組合函式時,建議使用 sharedBounds() 支援字型變更,例如在斜體和粗體之間轉換,或變更顏色。

在前述範例中,如果在兩種不同情境下將 Modifier.sharedBounds() 新增至 RowColumn,就能共用這兩者的邊界並執行轉場動畫,讓兩者之間的邊界彼此擴大:

@Composable
private fun MainContent(
    onShowDetails: () -> Unit,
    modifier: Modifier = Modifier,
    sharedTransitionScope: SharedTransitionScope,
    animatedVisibilityScope: AnimatedVisibilityScope
) {
    with(sharedTransitionScope) {
        Row(
            modifier = Modifier
                .padding(8.dp)
                .sharedBounds(
                    rememberSharedContentState(key = "bounds"),
                    animatedVisibilityScope = animatedVisibilityScope,
                    enter = fadeIn(),
                    exit = fadeOut(),
                    resizeMode = SharedTransitionScope.ResizeMode.ScaleToBounds()
                )
                // ...
        ) {
            // ...
        }
    }
}

@Composable
private fun DetailsContent(
    modifier: Modifier = Modifier,
    onBack: () -> Unit,
    sharedTransitionScope: SharedTransitionScope,
    animatedVisibilityScope: AnimatedVisibilityScope
) {
    with(sharedTransitionScope) {
        Column(
            modifier = Modifier
                .padding(top = 200.dp, start = 16.dp, end = 16.dp)
                .sharedBounds(
                    rememberSharedContentState(key = "bounds"),
                    animatedVisibilityScope = animatedVisibilityScope,
                    enter = fadeIn(),
                    exit = fadeOut(),
                    resizeMode = SharedTransitionScope.ResizeMode.ScaleToBounds()
                )
                // ...

        ) {
            // ...
        }
    }
}

圖 5. 兩個可組合項之間的共用邊界。

瞭解範圍

如要使用 Modifier.sharedElement(),可組合函式必須位於 SharedTransitionScope 中。SharedTransitionLayout 可組合項提供 SharedTransitionScope。務必將要共用元素的 UI 階層中位於同一個頂層點放在同一層。

一般來說,可組合項也應置於 AnimatedVisibilityScope 內。除非手動管理瀏覽權限,否則通常使用 AnimatedContent 切換可組合項、直接使用 AnimatedVisibility,或透過 NavHost 可組合函式提供。如要使用多個範圍,請將所需範圍儲存在 CompositionLocal 中,使用 Kotlin 中的 context 接收器,或將範圍做為參數傳遞至函式。

當您有多個需要追蹤的範圍,或多層巢狀結構階層時,請使用 CompositionLocalsCompositionLocal 可讓您選擇要儲存及使用的確切範圍。另一方面,使用內容接收器時,階層中的其他版面配置可能會意外覆寫提供的範圍。舉例來說,如果您有多個巢狀 AnimatedContent,範圍可能會遭到覆寫。

val LocalNavAnimatedVisibilityScope = compositionLocalOf<AnimatedVisibilityScope?> { null }
val LocalSharedTransitionScope = compositionLocalOf<SharedTransitionScope?> { null }

@Composable
private fun SharedElementScope_CompositionLocal() {
    // An example of how to use composition locals to pass around the shared transition scope, far down your UI tree.
    // ...
    SharedTransitionLayout {
        CompositionLocalProvider(
            LocalSharedTransitionScope provides this
        ) {
            // This could also be your top-level NavHost as this provides an AnimatedContentScope
            AnimatedContent(state, label = "Top level AnimatedContent") { targetState ->
                CompositionLocalProvider(LocalNavAnimatedVisibilityScope provides this) {
                    // Now we can access the scopes in any nested composables as follows:
                    val sharedTransitionScope = LocalSharedTransitionScope.current
                        ?: throw IllegalStateException("No SharedElementScope found")
                    val animatedVisibilityScope = LocalNavAnimatedVisibilityScope.current
                        ?: throw IllegalStateException("No AnimatedVisibility found")
                }
                // ...
            }
        }
    }
}

或者,如果您的階層並未具備深層巢狀結構,您也可以將範圍向下傳遞做為參數:

@Composable
fun MainContent(
    animatedVisibilityScope: AnimatedVisibilityScope,
    sharedTransitionScope: SharedTransitionScope
) {
}

@Composable
fun Details(
    animatedVisibilityScope: AnimatedVisibilityScope,
    sharedTransitionScope: SharedTransitionScope
) {
}

AnimatedVisibility 共用的元素

先前的範例說明如何搭配 AnimatedContent 使用共用元素,但共用元素也可以與 AnimatedVisibility 搭配使用。

舉例來說,在這個延遲格狀檢視畫面範例中,每個元素都會包裝在 AnimatedVisibility 中。點選項目時,內容會顯示視覺效果,從 UI 拉出至類似對話方塊的元件。

var selectedSnack by remember { mutableStateOf<Snack?>(null) }

SharedTransitionLayout(modifier = Modifier.fillMaxSize()) {
    LazyColumn(
        // ...
    ) {
        items(listSnacks) { snack ->
            AnimatedVisibility(
                visible = snack != selectedSnack,
                enter = fadeIn() + scaleIn(),
                exit = fadeOut() + scaleOut(),
                modifier = Modifier.animateItem()
            ) {
                Box(
                    modifier = Modifier
                        .sharedBounds(
                            sharedContentState = rememberSharedContentState(key = "${snack.name}-bounds"),
                            // Using the scope provided by AnimatedVisibility
                            animatedVisibilityScope = this,
                            clipInOverlayDuringTransition = OverlayClip(shapeForSharedElement)
                        )
                        .background(Color.White, shapeForSharedElement)
                        .clip(shapeForSharedElement)
                ) {
                    SnackContents(
                        snack = snack,
                        modifier = Modifier.sharedElement(
                            state = rememberSharedContentState(key = snack.name),
                            animatedVisibilityScope = this@AnimatedVisibility
                        ),
                        onClick = {
                            selectedSnack = snack
                        }
                    )
                }
            }
        }
    }
    // Contains matching AnimatedContent with sharedBounds modifiers.
    SnackEditDetails(
        snack = selectedSnack,
        onConfirmClick = {
            selectedSnack = null
        }
    )
}

圖 6.使用 AnimatedVisibility 的共用元素。

修飾符排序

對於 Modifier.sharedElement()Modifier.sharedBounds()修飾符鏈結的順序很重要,這點與 Compose 的其他部分相同。影響大小的修飾符放置位置不正確,可能會導致在共用元素比對期間發生視覺跳躍的情況。

舉例來說,如果您將邊框間距修飾符放在兩個共用元素的不同位置,動畫就會出現視覺上的差異。

var selectFirst by remember { mutableStateOf(true) }
val key = remember { Any() }
SharedTransitionLayout(
    Modifier
        .fillMaxSize()
        .padding(10.dp)
        .clickable {
            selectFirst = !selectFirst
        }
) {
    AnimatedContent(targetState = selectFirst, label = "AnimatedContent") { targetState ->
        if (targetState) {
            Box(
                Modifier
                    .padding(12.dp)
                    .sharedBounds(
                        rememberSharedContentState(key = key),
                        animatedVisibilityScope = this@AnimatedContent
                    )
                    .border(2.dp, Color.Red)
            ) {
                Text(
                    "Hello",
                    fontSize = 20.sp
                )
            }
        } else {
            Box(
                Modifier
                    .offset(180.dp, 180.dp)
                    .sharedBounds(
                        rememberSharedContentState(
                            key = key,
                        ),
                        animatedVisibilityScope = this@AnimatedContent
                    )
                    .border(2.dp, Color.Red)
                    // This padding is placed after sharedBounds, but it doesn't match the
                    // other shared elements modifier order, resulting in visual jumps
                    .padding(12.dp)

            ) {
                Text(
                    "Hello",
                    fontSize = 36.sp
                )
            }
        }
    }
}

相符的邊界

不相符的邊界:請注意,共用元素動畫需要調整為不正確的邊界,因此看起來有點不對勁

在共用元素修飾符「前」使用的修飾符會為共用元素修飾符提供限制,然後用於衍生初始和目標邊界,以及後續的邊界動畫。

共用元素修飾符後使用的修飾符會使用先前的限制,測量及計算子項的目標大小。共用元素修飾符會建立一系列動畫約束條件,將子項從初始大小逐漸轉換為目標大小。

例外狀況是,如果您在可組合項上使用 resizeMode = ScaleToBounds()Modifier.skipToLookaheadSize() 進行動畫。在這種情況下,Compose 會使用目標限制條件來安排子項,並使用比例因數執行動畫,而非變更版面配置大小。

不重複的鍵

使用複雜的共用元素時,建議您建立非字串的鍵,因為字串可能會出現比對錯誤。每個鍵都必須是唯一值,才能進行比對。例如,在 Jetsnack 中,我們會使用下列共用元素:

圖 7.這張圖片顯示 Jetsnack,每個 UI 部分皆有註解。

您可以建立列舉來代表共用元素類型。在這個範例中,整張點心資訊卡也可以出現在主畫面的多個不同位置,例如「熱門」和「推薦」區段。您可以建立包含 snackIdorigin (「熱門」/「建議」) 和共用元素 type 的鍵,以便共用:

data class SnackSharedElementKey(
    val snackId: Long,
    val origin: String,
    val type: SnackSharedElementType
)

enum class SnackSharedElementType {
    Bounds,
    Image,
    Title,
    Tagline,
    Background
}

@Composable
fun SharedElementUniqueKey() {
    // ...
            Box(
                modifier = Modifier
                    .sharedElement(
                        rememberSharedContentState(
                            key = SnackSharedElementKey(
                                snackId = 1,
                                origin = "latest",
                                type = SnackSharedElementType.Image
                            )
                        ),
                        animatedVisibilityScope = this@AnimatedVisibility
                    )
            )
            // ...
}

建議使用資料類別做為鍵,因為這類類別會實作 hashCode()isEquals()

手動管理共用元素的顯示設定

如果沒有使用 AnimatedVisibilityAnimatedContent,可以自行管理共用元素的瀏覽權限。請使用 Modifier.sharedElementWithCallerManagedVisibility() 並提供您自己的條件式,以決定何時應顯示項目:

var selectFirst by remember { mutableStateOf(true) }
val key = remember { Any() }
SharedTransitionLayout(
    Modifier
        .fillMaxSize()
        .padding(10.dp)
        .clickable {
            selectFirst = !selectFirst
        }
) {
    Box(
        Modifier
            .sharedElementWithCallerManagedVisibility(
                rememberSharedContentState(key = key),
                !selectFirst
            )
            .background(Color.Red)
            .size(100.dp)
    ) {
        Text(if (!selectFirst) "false" else "true", color = Color.White)
    }
    Box(
        Modifier
            .offset(180.dp, 180.dp)
            .sharedElementWithCallerManagedVisibility(
                rememberSharedContentState(
                    key = key,
                ),
                selectFirst
            )
            .alpha(0.5f)
            .background(Color.Blue)
            .size(180.dp)
    ) {
        Text(if (selectFirst) "false" else "true", color = Color.White)
    }
}

目前限制

這些 API 有一些限制。最值得注意的是:

  • 不支援 View 和 Compose 之間的互通性。包括任何包裝 AndroidView 的可組合項,例如 Dialog
  • 以下項目不支援自動動畫:
    • 共用圖片可組合項
      • ContentScale 預設不會顯示動畫。並會對齊設定的結尾 ContentScale
    • 形狀裁剪:不支援在形狀之間自動動畫效果,例如在項目轉換時從正方形到圓形動畫。
    • 針對不支援的情況,請使用 Modifier.sharedBounds() 而非 sharedElement(),然後在項目中新增 Modifier.animateEnterExit()