您的位置:首页 > 其它

TextInputLayout是一个能够把EditText包裹在当中的一个布局,当输入文字时,它可以把Hint文字飘到EditText的上方。

2016-05-10 09:28 369 查看
如何使用Android Design中的TextInputLayout
字数337 阅读3000 评论0 喜欢9
TextInputLayout是一个能够把EditText包裹在当中的一个布局,当输入文字时,它可以把Hint文字飘到EditText的上方。

TextInputLayout is a layout which wraps an EditText to show a floating label when the hint is hidden due to the user inputting text. Also supports showing an error via setErrorEnabled(boolean) and [setError(CharSequence)](https://developer.android.com/reference/android/support/design/widget/TextInputLayout.html#setError(java.lang.CharSequence).

效果如下

TextInputLayout.gif
实现步骤
0x01. 添加依赖
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
}
0x02. UI代码
使用TextInputLayout包裹住EditText

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

<EditText android:id="@+id/your_matchcode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:saveEnabled="false"
android:maxLength="48"
android:digits="1234567890qwertyuiopasdfghjklzxcvbnm "
android:hint="请设定匹配码"/>
</android.support.design.widget.TextInputLayout>
0x03. 添加逻辑判断
在EditText中添加输入监听代码,注意在onTextChanged中调用才有实时效果

mYourMatchcode.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

}

//检测错误输入,当输入错误时,hint会变成红色并提醒
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//检查实际是否匹配,由自己实现
if (checkType(charSequence.toString())) {
mYourMatchcodeHolder.setErrorEnabled(true);
mYourMatchcodeHolder.setError("请检查格式");
return;
} else {
mYourMatchcodeHolder.setErrorEnabled(false);
}
}

@Override public void afterTextChanged(Editable editable) {

}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: