回應焦點

提供視覺提示,讓焦點變得更加容易

儘管 Material 主題中的所有可聚焦元素都已有焦點樣式 您可能需要加入一些視覺元素 以便找出焦點所在理想的做法是將 元素的顏色與背景形成明顯對比:

var color by remember { mutableStateOf(Color.White) }
Card(
    modifier = Modifier
        .onFocusChanged {
            color = if (it.isFocused) Red else White
        }
        .border(5.dp, color)
) {}

在本例中,remember 是用來儲存橫跨多個部分的邊框顏色 重新組成,而元素外框每次都會更新 增減或失焦

實作進階視覺提示

Jetpack Compose 還能讓您製作更複雜、更進階的視覺元素 還會顯示更適合您 UI 的提示

  1. 首先建立 IndicationInstance,在 UI 中以視覺化方式繪製所需提示:
    private class MyHighlightIndicationNode(private val interactionSource: InteractionSource) :
        Modifier.Node(), DrawModifierNode {
        private var isFocused = false
    
        override fun onAttach() {
            coroutineScope.launch {
                var focusCount = 0
                interactionSource.interactions.collect { interaction ->
                    when (interaction) {
                        is FocusInteraction.Focus -> focusCount++
                        is FocusInteraction.Unfocus -> focusCount--
                    }
                    val focused = focusCount > 0
                    if (isFocused != focused) {
                        isFocused = focused
                        invalidateDraw()
                    }
                }
            }
        }
    
        override fun ContentDrawScope.draw() {
            drawContent()
            if (isFocused) {
                drawRect(size = size, color = Color.White, alpha = 0.2f)
            }
        }
    }
    
  2. 接下來,請建立 Indication 並記住已聚焦的狀態:
    object MyHighlightIndication : IndicationNodeFactory {
        override fun create(interactionSource: InteractionSource): DelegatableNode {
            return MyHighlightIndicationNode(interactionSource)
        }
    
        override fun hashCode(): Int = -1
    
        override fun equals(other: Any?) = other === this
    }
  3. 透過 indication() 修飾符將 IndicationInteractionSource 新增至 UI:
    var interactionSource = remember { MutableInteractionSource() }
    
    Card(
        modifier = Modifier
            .clickable(
                interactionSource = interactionSource,
                indication = MyHighlightIndication,
                enabled = true,
                onClick = { }
            )
    ) {
        Text("hello")
    }

瞭解焦點狀態

一般來說,每當焦點的狀態變更時,就會觸發 FocusEventfocusable() 修飾符的父項可以使用 onFocusChanged() 修飾符。

如果需要瞭解焦點狀態,可以搭配使用這些 API 使用 onFocusChanged 修飾符:

  • 如果已附加修飾符的可組合函式,isFocused 會傳回 true 聚焦
  • hasFocus 的運作方式與 isFocused 類似,但有顯著差異: 而不是只檢查目前的項目,而是檢查該元素是否 聚焦兒童
  • 每當保留焦點,isCaptured 都會傳回 true。這麼做會發生 例項,當 TextField 包含不正確的資料時,因此嘗試聚焦 不會清除焦點

這些欄位顯示如下:

Modifier.onFocusChanged {
    val isFocused = it.isFocused
    val hasFocus = it.hasFocus
    val isCaptured= it.isCaptured
}
敬上

目前沒有任何建議。

建議 Google 帳戶。