代码之家  ›  专栏  ›  技术社区  ›  Harvey

我在哪里可以找到androidx.composite.foundation.samples。基本文本字段自定义输入转换示例

  •  0
  • Harvey  · 技术社区  · 4 周前

    我正在阅读InputTransformation的文档,它将我带到下面的一个示例- androidx.compose.foundation.samples。基本文本字段自定义输入转换示例

    这是我在安卓工作室看到的

    enter image description here

    问题是我在互联网上找不到这个样本,或者至少我觉得不够难。有人知道我在哪里可以看到这些样品吗?

    1 回复  |  直到 4 周前
        1
  •  0
  •   BenjyTec    4 周前

    看看 Google Code Search 。在那里你可以找到Android、AndroidX和其他的源代码。当你进入 androidx.compose.foundation.samples.BasicTextFieldCustomInputTransformationSample 在那里,你会发现 BasicTextFieldSamples 文件行 320 :

    @Sampled
    @Composable
    fun BasicTextFieldCustomInputTransformationSample() {
        // Demonstrates how to create a custom and relatively complex InputTransformation.
        val state = remember { TextFieldState() }
        BasicTextField(state, inputTransformation = {
            // A filter that always places newly-input text at the start of the string, after a
            // prompt character, like a shell.
            val promptChar = '>'
    
            fun CharSequence.countPrefix(char: Char): Int {
                var i = 0
                while (i < length && get(i) == char) i++
                return i
            }
    
            // Step one: Figure out the insertion point.
            val newPromptChars = asCharSequence().countPrefix(promptChar)
            val insertionPoint = if (newPromptChars == 0) 0 else 1
    
            // Step two: Ensure text is placed at the insertion point.
            if (changes.changeCount == 1) {
                val insertedRange = changes.getRange(0)
                val replacedRange = changes.getOriginalRange(0)
                if (!replacedRange.collapsed && insertedRange.collapsed) {
                    // Text was deleted, delete forwards from insertion point.
                    delete(insertionPoint, insertionPoint + replacedRange.length)
                }
            }
            // Else text was replaced or there were multiple changes - don't handle.
    
            // Step three: Ensure the prompt character is there.
            if (newPromptChars == 0) {
                insert(0, ">")
            }
    
            // Step four: Ensure the cursor is ready for the next input.
            placeCursorAfterCharAt(0)
        })
    }
    

    事实证明,它与的文档中提供的片段完全相同 InputTransformation .