由于 Google 引入了 TextInputLayout 作为 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 下方显示错误,您只需在TextInputLayout 上调用#setError(不在子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();