Material Design学习-----TextInputLayout

  TextInputLayout是为EditText提供了一种新的实现和交互方式。在传统的EditText中存在一个hint属性,是说在editext中没有内容时,默认的提示信息。当想edittext中输入信息的时候会自动消失。而在TextInputLayout中当想edittext中输入信息的时候,这些提示信息会经过动画的方式,移动到控件顶部继续存在,同时还会提示错误的信息,实现了一个更好的交互效果。实现的效果以下图:android

  一、实现方式布局

   TextInputLayout和通常的layout同样,是一个容器,只要把想实现效果的edittext放在容器中就能够了,可是同时TextInputLayout和scrollview同样,其中只能放一个控件做为其子控件。实现代码以下:动画

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical">
 6     <android.support.design.widget.TextInputLayout
 7         android:id="@+id/username_layout"
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content">
10         <EditText
11             android:id="@+id/username"
12             android:layout_width="match_parent"
13             android:layout_height="wrap_content"
14             android:hint="用户名"/>
15     </android.support.design.widget.TextInputLayout>
16     <android.support.design.widget.TextInputLayout
17         android:id="@+id/pwd_layout"
18         android:layout_width="match_parent"
19         android:layout_height="wrap_content">
20         <EditText
21             android:id="@+id/pwd"
22             android:layout_width="match_parent"
23             android:layout_height="wrap_content"
24             android:hint="密码"/>
25     </android.support.design.widget.TextInputLayout>
26     <Button
27         android:id="@+id/btn_b"
28         android:layout_width="match_parent"
29         android:layout_height="wrap_content" />
30 </LinearLayout>

  从上面能够看出,要想让多个edittext实现效果,就要使用多个TextInputLayout进行嵌套。spa

  要想让结果实现,光是在xml布局文件中实现仍是不够的,同时还须要在Activity中实现相应的设置:code

1 text1= (TextInputLayout) findViewById(R.id.username_layout);
2         text2= (TextInputLayout) findViewById(R.id.pwd_layout);
3         btn= (Button) findViewById(R.id.btn_b);
4         text1.setHint("用户名");
5         text2.setHint("密码");

  同时要是想要实现错误提示信息的话,就要设置相应的setErrorEnabled方法和setErrror方法:xml

1 text1.setErrorEnabled(true); 
2 text1.setError("密码错误");

  二、自定义样式  blog

  你可能还想作最后一件事,改变TextInputLayout控件的颜色。默认AppCompact会把它设置成绿色的,可是颇有可能这个颜色会和你的颜色主题(color palette)冲突。utf-8

 

谷歌把Design Support Library写的很好。每个控件的颜色都是直接经过主题颜色绘制的,在 style.xml 中指定。打开它添加colorAccent 到主题以改变表单的颜色。get

1 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
2     <item name="colorAccent">#3498db</item>
3 </style>
相关文章
相关标签/搜索