LoginSignup
2

More than 1 year has passed since last update.

Jetpack ComposeのTextField(EditText)についての色々 [Android Kotlin]

Last updated at Posted at 2021-06-26

はじめに

Jetpack ComposeのEditText的存在 TextField の基本的なことを書いていきます。
触り始めたその日に書いているので訂正すべき点などあったらコメントお願いします!
参考
https://developer.android.com/jetpack/compose/state#state-in-composables
https://www.youtube.com/watch?v=O_MmOP5fjUg

では、早速

MainAcitvity.kt
@Composable
fun textField(){
    TextField(
        value = "キョン",
        onValueChange = {}
    )
}

TextField()でTextFieldを起動して引数で色々設定していく形ですね。
value → TextFieldの値を設定
onValueChange → TextFieldの値の変化を受け取る
という役割があります。

問題点1 TextFieldの値を編集できない

MainActivity.kt
@Composable
fun textField(){
    val fieldValue = remember { mutableStateOf("キョン") }
    TextField(
        value = fieldValue.value,
        onValueChange = { newValue ->
            fieldValue.value = newValue
        })
}

これでユーザーが値を編集できます!onValueChangeでTextFieldの値に変化があったら値を取得してfieldValueに代入。valueにfieldValueを代入でTextFieldの値が置き換わる。という感じです。
remember()、mutableStateOf()は正直雰囲気で使っていて、どう働いているか説明できないので公式のリンクを貼っておきます。https://developer.android.com/jetpack/compose/state#state-in-composables

問題点2 画面回転すると値がリセットされる

ViewModelは画面が回転しても値を保持してくれるのでViewModelを使って解決していきます。

MainViewModel.kt
class MainViewModel: ViewModel() {
    val query = mutableStateOf("キョン")

    fun onQueryChanged(newValue: String){
        query.value = newValue
    }
}
MainActivity.kt
@Composable
    fun textField() {
        val fieldValue = viewModel.query.value

                TextField(value = fieldValue,
                    onValueChange = { newValue ->
                        viewModel.onQueryChanged(newValue)
                    })
    }

ViewModelのqueryを参照しTextFieldに代入する。
ViweModel内でqueryの値を更新する関数を定義し、MainActivityのonValueChangeでその関数を呼んであげる。
この二つによって画面が回転しても値がリセットされないTextFieldが出来ます!
またViewModelに値を保存しておけばButtonが押されたらTextFieldの値を取得することも簡単に実装できますね。

@Composable
fun Button() {
    Button(
        onClick = {  
         println(viewModel.query.value)
 },
    ) {
        Text("Button")
    }
}

以上

F399368B-F1B2-4D0F-BBB0-93BD6C55E551.gif

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2