TextInputLayout使用
What is TextInputLayout
這個Layout是用來套在EditText外面的,換言之,TextInputLayout不能單獨存在,必須配合EditText一起使用,那么它有什么功能?
一.設置提示語,在輸入狀態下提示語依然可見(在EditText上方)
二.設置錯誤提示語,當EditText中的內容不符合要求時,可以在EditText下方顯示錯誤信息
效果如下


用法
xml中聲明一個TextInputLayout(里面套一個EditText)
<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
java文件中
final TextInputLayout inputLayout= (TextInputLayout) findViewById(R.id.input_layout);
inputLayout.setHint("請輸入姓名");
EditText text=inputLayout.getEditText();
inputLayout.setErrorEnabled(true);
text.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>6){
inputLayout.setError("姓名長度不能大于6");
}else{
inputLayout.setError(null);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
在其他博客中還看到有這樣一種寫法的
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>6){
inputLayout.setErrorEnabled(true);
inputLayout.setError("姓名長度不能大于6");
}else{
//inputLayout.setErrorEnabled(false);
inputLayout.setErrorEnabled(false);
}
}
實測這種寫法有BUG(在23.0.0下)
具體表現為第一次長度超過6時顯示錯誤信息,然后小于6時錯誤信息消失,輸入內容長度再度超過6時,錯誤信息不再顯示。
看起來好像是一旦調用了setErrorEnabled(false);再次執行setErrorEnabled(true);都是無效的了。
google了一下也有相關討論
Issue 190355: TextInputLayout setError() will not show an error after it is cleared
Maybe已經解決了?

浙公網安備 33010602011771號