前沿

  上一篇介绍了NavigationView的主要使用方式,本章主要介绍TextInputLayout的使用方式。

  TextInputLayout——EditText悬浮标签

  TextInputLayout主要作为EditText的父容器来使用,不能单独使用。TextInputLayout解决了EditText输入后hint文字消失的情况,当用户在EditText开始输入后,hint部分的文字会浮动到EditText的上方,而且还可以添加输入错误时的提示信息,显示在editText的下方,效果如下:

  

  使用步骤:

  (1)xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"> <android.support.design.widget.TextInputLayout
android:id="@+id/usernameWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"> <EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
</RelativeLayout>

  (2)Java代码调用

final TextInputLayout textInputLayout = (TextInputLayout) findViewById(R.id.usernameWrapper);
textInputLayout.setHint("Username");
EditText editText = textInputLayout.getEditText();//直接通过getEditText()获得EditText控件即可 editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length() > 3) {//这里可以加入正则判断
textInputLayout.setError("Password error");
textInputLayout.setErrorEnabled(true); //一定要在setError方法之后执行才可
} else {
textInputLayout.setErrorEnabled(false);//不满足条件需要设置为false
}
} @Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}

  此外可以通过TextInputLayout如下两个属性来设置hint和error的字体

app:errorTextAppearance="@style/FloatingStyle"
app:hintTextAppearance="@style/FloatingStyle"

  /style/FloatingStyle

 <style name="FloatingStyle" parent="@android:style/TextAppearance">
<item name="android:textColor">@color/colorPrimaryDark</item>
<item name="android:textSize">12sp</item>
</style>

最新文章

  1. 麦克斯韦方程组 (Maxwell&#39;s equation)的简单解释
  2. 关于url传参中文乱码问题
  3. Easyui datebox 限制时间选择范围
  4. MySQL安装及主从配置
  5. UISegment属性
  6. sqlserver模糊查询【转】
  7. (补)PSP三张表
  8. 自己写的中间层..基于通讯组件 RTC
  9. SQL SERVER中的逻辑读,预读和物理读
  10. php 防止SQL注入函数
  11. 在线阅读PDF文件js插件——pdf.js
  12. 在Web.config中配置handler
  13. 汇编实现: C库常见函数,串操作指令作用
  14. 索引-mysql
  15. 牛客网 223C 区区区间间间(单调栈)
  16. 利用(CMD)在Django中创建文件
  17. 【MySQL】局域网内:在一台电脑访问另一台电脑的mysql数据库
  18. CSS2.0中最常用的18条技巧
  19. tornado.gen 模块解析
  20. c# 使用 HttpWebRequest模拟登陆(附带验证码)

热门文章

  1. vertical-align两种应用场合
  2. 下载image或者其他文件
  3. MySQL忘记root用户密码修改方法
  4. 与众不同 windows phone (42) - 8.0 相机和照片: 通过 PhotoCaptureDevice 捕获照片
  5. Discuz API的延伸
  6. [转] 基于 Apache Mahout 构建社会化推荐引擎
  7. 关闭Eclipse中自动弹出console的功能
  8. javascript indexOf startWith
  9. mac下eclipse的svn(即svn插件)怎么切换账号?
  10. java微信开发