batchのブログ

知見の備忘録

TextInputLayoutとTextInputEditTextのerrorとかの違いについての豆知識だよ

基本的に,TextInputLayoutの子にTextInputEditTextを入れて使う.

TextInputLayoutの設定

android:hintを設定することでhintを設定することができる.これを設定するだけでEditTextをタップしたときにかっこいいアニメーション付きでhintが上に移動するやつが実装できる.hintの色はapp:hintTextColorで設定できる.

よくある,ボタンを押したときに中身が入力されていないときのエラー表示については,TextInputLayoutにapp:errorEnabled="true"を設定してあげればできるようになる.あとはKotlin側で書く.だいたい下の様な感じ.

button.setOnClickListener {
            var message: String
            when(TextUtils.isEmpty(edit_text.text)) {
                true -> {
                    message = "入力されていません"
                    text_input.error = message
                    edit_text.error = message
                }
                false -> {
                    message = "入力されています"
                    text_input.error = null
                    edit_text.error = null
                }
            }

ここで抑えておきたいのは親のTextInputLayoutとその子のTextInputEditTextの両方にerrorの処理を書けてそれぞれ挙動が違うこと.
TextInputLayoutに書くとこう.
f:id:batch08:20200226204135p:plain

TextInputEditTextに書くとこう.
f:id:batch08:20200226204226p:plain

両方組み合わせることもできる. ちなみに,helperっていうのを設定すればerrorと同じ位置にエラー時以外に下のラインの下にメッセージを表示させることができる.全体的にサンプルで作成したのは以下の感じ.

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/text_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"
        android:hint="This is hint"
        app:hintTextColor="@android:color/holo_blue_dark"
        app:errorEnabled="true"
        app:errorTextColor="@color/colorAccent"
        app:errorIconTint="@color/colorAccent"
        app:helperText="This is helper"
        app:helperTextTextColor="@android:color/black">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/holo_green_dark"
            android:maxLines="1"/>
    </com.google.android.material.textfield.TextInputLayout>

hintTextColortextColotHintの違いについて.
hintTextColorはEditTextをタップしたときにシュッって上にいったhintの色のこと.textColorHintはまだタップする前に表示されているhintの色のこと.
以下, app:hintTextColor="@android:color/holo_green_dark" のとき
f:id:batch08:20200226204256p:plain android:textColorHint="@android:color/holo_blue_dark"のとき
f:id:batch08:20200226204328p:plain