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

如何使用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) {

      }
    });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值