Android – How to use EditText or TextInput widget in Jetpack compose

androidandroid-compose-textfieldandroid-jetpack-composeandroidx

I was exploring Jetpack compose by trying a few widgets like Image and EditText.

For text input, it has EditableText. I have tried below code but it is not showing anything in UI

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            loadUi()
        }
    }

    @Composable
    fun loadUi() {
        CraneWrapper {
            MaterialTheme {
                val state = +state { EditorState("") }
                EditableText(
                    value = state.value,
                    onValueChange = { state.value = it },
                    editorStyle = EditorStyle(
                        textStyle = TextStyle(
                            fontSize = (50f)
                        )
                    )
                )
            }
        }
    }
}

What I am missing here? Any help would be appreciated!

Best Solution

As stated in Gabriele Mariotti's answer, this is the right way to do it:

var text by rememberSaveable { mutableStateOf("Text") }

TextField(
    value = text,
    onValueChange = {
        text = it
    },
    label = { Text("Label") }
)

If however, you encounter an error that states:

Type 'TypeVariable(T)' has no method 'getValue(MainActivity, KProperty<*>)' and thus it cannot serve as a delegate

Simply add these two imports to your file and you'd be good:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
Related Question