共用元素轉場效果可讓您在內容一致的可組合項之間流暢轉換。這類元素通常用於導覽,可讓您在使用者瀏覽不同畫面時,以視覺方式連結這些畫面。
舉例來說,在下方影片中,您可以看到點心的圖片和標題從清單頁面分享到詳細資料頁面。
在 Compose 中,有幾個高階 API 可協助您建立共用元素:
SharedTransitionLayout:實作共用元素轉換所需的最外層版面配置。提供SharedTransitionScope。可組合項必須位於SharedTransitionScope中,才能使用共用元素修飾符。Modifier.sharedElement():這個修飾符會向SharedTransitionScope標記應與另一個可組合項配對的可組合項。Modifier.sharedBounds():這個修飾符會向SharedTransitionScope標記,指出這個可組合函式的邊界應做為容器邊界,用於發生轉場效果的位置。與sharedElement()不同,sharedBounds()專為視覺上不同的內容而設計。
在 Compose 中建立共用元素時,必須瞭解這些元素如何與疊加層和裁剪功能搭配運作。請參閱「裁剪和疊加層」一節,進一步瞭解這個重要主題。
基本用法
本節將建構以下轉場效果,從較小的「清單」項目轉換為較大的詳細項目:
使用 Modifier.sharedElement() 的最佳方式是搭配 AnimatedContent、AnimatedVisibility 或 NavHost,因為這會自動管理可組合項之間的轉換。
起點是現有的基本 AnimatedContent,其中包含 MainContent 和 DetailsContent 可組合函式,然後再新增共用元素:
AnimatedContent,不使用任何共用元素轉場效果。如要讓共用元素在兩個版面配置之間建立動畫效果,請使用
SharedTransitionLayout包圍AnimatedContent可組合項。SharedTransitionLayout和AnimatedContent的範圍會傳遞至MainContent和DetailsContent: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 ) } } }
在兩個相符的可組合項上,將
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。
這會產生下列自動動畫:
您可能會注意到,整個容器的背景顏色和大小仍使用預設的 AnimatedContent 設定。
共用邊界與共用元素
Modifier.sharedBounds() 與 Modifier.sharedElement() 類似。不過,修飾符有以下差異:
sharedBounds()適用於視覺上不同,但應在狀態之間共用相同區域的內容,而sharedElement()則預期內容相同。- 使用
sharedBounds()時,在兩種狀態之間轉換時,進入和離開畫面的內容會顯示,而使用sharedElement()時,只有目標內容會在轉換邊界中算繪。Modifier.sharedBounds()具有enter和exit參數,可用於指定內容轉換方式,類似於AnimatedContent的運作方式。 sharedBounds()最常見的用途是容器轉換模式,而sharedElement()的用途範例則是主頁橫幅轉場效果。- 使用
Text可組合項時,建議使用sharedBounds()支援字型變更,例如在斜體和粗體之間轉換,或變更顏色。
延續上一個範例,在兩種不同情境中,將 Modifier.sharedBounds() 新增至 Row 和 Column,即可共用兩者的邊界並執行轉場動畫,讓兩者之間能互相放大:
@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() ) // ... ) { // ... } } }
瞭解範圍
如要使用 Modifier.sharedElement(),可組合函式必須位於 SharedTransitionScope 中。SharedTransitionLayout 可組合項提供 SharedTransitionScope。請務必將其放置在 UI 階層中包含要共用元素的相同頂層點。
一般來說,可組合項也應放在 AnimatedVisibilityScope 內。這通常是透過使用 AnimatedContent 在可組合項之間切換,或直接使用 AnimatedVisibility,或透過 NavHost 可組合函式提供,除非您手動管理可見度。如要使用多個範圍,請將所需範圍儲存在 CompositionLocal 中、使用 Kotlin 中的內容接收器,或將範圍做為參數傳遞至函式。
如果您有多個範圍需要追蹤,或有深層巢狀階層,請使用 CompositionLocals。CompositionLocal 可讓您選擇要儲存及使用的確切範圍。另一方面,使用情境接收器時,階層中的其他版面配置可能會不小心覆寫提供的範圍。舉例來說,如果您有多個巢狀 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( sharedContentState = rememberSharedContentState(key = snack.name), animatedVisibilityScope = this@AnimatedVisibility ), onClick = { selectedSnack = snack } ) } } } } // Contains matching AnimatedContent with sharedBounds modifiers. SnackEditDetails( snack = selectedSnack, onConfirmClick = { selectedSnack = null } ) }
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 包含下列共用元素:
您可以建立列舉來代表共用元素類型。在這個範例中,整個點心資訊卡也可以顯示在主畫面的多個不同位置,例如「熱門」和「推薦」部分。您可以建立一個鍵,其中包含 snackId、origin (「熱門」/「推薦」),以及要共用的共用元素 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() 和 equals()。
手動管理共用元素的顯示設定
如果您不使用 AnimatedVisibility 或 AnimatedContent,可以自行管理共用元素的顯示設定。請使用 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或ModalBottomSheet。 - 系統不支援下列項目的自動動畫:
- 共用圖片可組合項:
ContentScale預設不會顯示動畫。並貼齊設定的結束時間ContentScale。
- 形狀裁剪:不支援形狀之間的自動動畫,例如在項目轉換時從正方形變成圓形。
- 如果是未支援的情況,請使用
Modifier.sharedBounds()而非sharedElement(),並在項目中加入Modifier.animateEnterExit()。
- 共用圖片可組合項: