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 中的情境接收器,或是將範圍做為參數傳遞至函式。

當您有多個需要追蹤的範圍,或多層巢狀結構階層時,請使用 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 搭配使用。

例如,在此 Lazy 格線範例中,每個元素都會納入 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()