焦點狀態提供清楚的視覺提示,協助使用者瞭解目前哪個 UI 元素具有輸入焦點。根據預設,所有互動式 Material 3 元件都提供內建焦點指示。
Material Design 主題設定焦點指示
Material 元件會使用 ripple 函式和 LocalIndication 繪製視覺狀態變更。如要將標準 Material 焦點回饋附加至自訂元件:
- 使用
remember { MutableInteractionSource() }建立MutableInteractionSource。 - 將互動來源和
ripple()傳遞至indication修飾符。
val interactionSource = remember { MutableInteractionSource() } Box( modifier = Modifier .clickable( interactionSource = interactionSource, indication = null ) { /* onClick */ } .indication( interactionSource = interactionSource, indication = ripple() ) ) { Text("Custom component with Material ripple") }
實作自訂焦點指示
如要自訂視覺提示 (例如縮放、邊框或發光效果):
- 建立
IndicationNodeFactory。 - 觀察元素
InteractionSource發出的焦點互動。 - 使用
indication修飾符套用自訂指示。
var interactionSource = remember { MutableInteractionSource() } Card( modifier = Modifier .clickable( interactionSource = interactionSource, indication = MyHighlightIndication, enabled = true, onClick = { } ) ) { Text("hello") }