Googleの説明に従ってエラーメッセージを表示するAndroid EditTextを設計する 質問する

Googleの説明に従ってエラーメッセージを表示するAndroid EditTextを設計する 質問する

EditText次のような onError が必要です:

ここに画像の説明を入力してください

onError を呼び出すと、代わりに次のようになります。

ここに画像の説明を入力してください

注: アプリは SDK 19 (4.4.2) で実行されています

最小SDKは1

これを自動的に実行する setError に似たメソッドはありますか、それともそのためのコードを記述する必要がありますか?

ありがとう

ベストアンサー1

TextInputLayoutGoogle がの一部として を導入したため、サードパーティのライブラリを使用する必要はありませんdesign-support-library

基本的な例は次のとおりです。

レイアウト

<android.support.design.widget.TextInputLayout
    android:id="@+id/text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:errorEnabled="true">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />

</android.support.design.widget.TextInputLayout>

注記:app:errorEnabled="true"の属性として設定すると、TextInputLayoutエラーが表示された後はサイズが変更されず、基本的にスペースがブロックされます。

コード

の下にエラーを表示するには、(子ではなく)をEditText呼び出すだけです。#setErrorTextInputLayoutEditText

TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setError("You need to enter a name");

結果

エラーメッセージ付きの編集テキストを示す画像

エラーを非表示にして色合いをリセットするには、 を呼び出すだけですtil.setError(null)


注記

を使用するには、依存関係TextInputLayoutに以下を追加する必要がありますbuild.gradle

dependencies {
    compile 'com.android.support:design:25.1.0'
}

カスタムカラーの設定

デフォルトでは、 の線はEditText赤になります。別の色を表示する必要がある場合は、 を呼び出すとすぐに次のコードを使用できますsetError

editText.getBackground().setColorFilter(getResources().getColor(R.color.red_500_primary), PorterDuff.Mode.SRC_ATOP);

これをクリアするには、次のように関数を呼び出すだけですclearColorFilter

editText.getBackground().clearColorFilter();

おすすめ記事