在 Jetpack Compose Glimmer 中,surface 構成元素是基本建構區塊,代表按鈕和資訊卡等元件的獨立視覺區域或實體邊界。
表面負責下列視覺和物理屬性:
- 剪裁:將子項剪裁成指定形狀。
- 邊框:繪製內框,強調元件邊界。當焦點位於該項目時,系統會繪製較寬的邊框,並醒目顯示焦點。
- 背景:為表面區域套用背景顏色。
- 深度效果:根據元件的狀態 (例如預設與焦點),算繪
DepthEffect陰影。 - 內容顏色:提供介面內文字和圖示的顏色,預設會根據背景顏色計算。
- 互動狀態:在表面按下時繪製按下疊加層,並在聚焦時繪製較寬的醒目顯示邊框。
範例:建立介面
下列程式碼會建立具有裁剪、背景和預設邊框的介面:
@Composable fun SurfaceSample() { Box(Modifier.surface().padding(horizontal = 24.dp, vertical = 20.dp)) { Text("This is a surface") } }
Interaction and Focus
Surfaces aren't focusable by default, so users can't interact with them. In most
cases, surfaces should be interactive to let users consistently move focus and
navigate between components. You can use the Compose focusable modifer
for surfaces that are only intended to be focusable, or the Compose
clickable modifer and other modifiers for surfaces that require actions.
You can create a focusable surface by combining a surface modifier with the
focusable modifier:
@Composable fun FocusableSurfaceSample() { val interactionSource = remember { MutableInteractionSource() } Box( Modifier.surface( // Provide the same interaction source here and to focusable to make sure that // surface appears focused when interacted with. interactionSource = interactionSource ) .focusable(interactionSource = interactionSource) .padding(horizontal = 24.dp, vertical = 20.dp) ) { Text("This is a focusable surface") } }
Key points about the code
- Shared interaction source: Both .
surface()and .focusable()must share the sameinteractionSource. This lets the surface react to focus changes.
Similarly, you can create a clickable surface:
@Composable fun ClickableSurfaceSample() { val interactionSource = remember { MutableInteractionSource() } Box( Modifier.surface( // Provide the same interaction source here and to clickable to make sure that // surface appears focused and pressed when interacted with interactionSource = interactionSource ) .clickable(interactionSource = interactionSource, onClick = {}) .padding(horizontal = 24.dp, vertical = 20.dp) ) { Text("This is a clickable surface") } }
程式碼重點
共用互動來源:兩者皆是。
surface()和。clickable()必須共用相同的interactionSource。這可確保視覺狀態 (例如按壓或焦點) 會同步處理,讓介面以視覺方式回應使用者輸入內容。修飾符順序:修飾符的順序非常重要。因為 。
surface()會剪輯版面配置,並將其放在 之前。clickable()可確保觸控目標受限於表面的形狀。如果 .clickable(),互動區域可能會超出元件可見的裁剪界線。
SurfaceDepthEffect
SurfaceDepthEffect 類別會管理互動狀態之間的陰影轉場效果:
depthEffect:表面處於預設狀態時使用的陰影效果。focusedDepthEffect:表面聚焦時使用的陰影效果。