EditText
次のような onError が必要です:
onError を呼び出すと、代わりに次のようになります。
注: アプリは SDK 19 (4.4.2) で実行されています
最小SDKは1
これを自動的に実行する setError に似たメソッドはありますか、それともそのためのコードを記述する必要がありますか?
ありがとう
ベストアンサー1
TextInputLayout
Google がの一部として を導入したため、サードパーティのライブラリを使用する必要はありません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
呼び出すだけです。#setError
TextInputLayout
EditText
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();