Search code examples
androidandroid-jetpack-compose

Where can I find the androidx.compose.foundation.samples.BasicTextFieldCustomInputTransformationSample


I'm reading the document of InputTransformation and it leads me to a sample under - androidx.compose.foundation.samples.BasicTextFieldCustomInputTransformationSample

This is what I see from Android Studio

enter image description here

The thing is I can't find that sample anywhere on the internet or at least I didn't find it hard enough. Does anyone have any idea where I can see those samples?


Solution

  • Have a look at the Google Code Search. There you can find the source code of Android, AndroidX, and others. When you enter androidx.compose.foundation.samples.BasicTextFieldCustomInputTransformationSample there, you will find the BasicTextFieldSamples file line 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)
        })
    }
    

    As it turns out, it is the exact same snippet that is provided in the documentation for InputTransformation.