在哪里可以找到 androidx.compose.foundation.samples.BasicTextFieldCustomInputTransformationSample

问题描述 投票:0回答:1

我正在阅读 InputTransformation 的文档,它引导我找到以下示例 - androidx.compose.foundation.samples.BasicTextFieldCustomInputTransformationSample

这是我从 Android Studio 看到的

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

android android-jetpack-compose
1个回答
0
投票

查看 Google 代码搜索。在那里你可以找到 AOSP 的完整源代码。当您在那里输入

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
的文档中提供的片段完全相同。

© www.soinside.com 2019 - 2024. All rights reserved.