Introduction

同样的,这个控件也是Material Design中的控件。

Google I/O 2015 ,谷歌意识到向后兼容是实现material design的重要部分。当然support library,比如appcompat-v4 和 appcompat-v7是解决方案的一部分。

但是Theme.AppCompat 并没有实现谷歌官方应用中用到的每个material组建。其中一个重要的特性就是AppCompat theme没有提供一个显示在EditText上方的浮动标签。

比如下图所示:

在Google I/O 2015期间,安卓团队发布了一个崭新的兼容库,Design Support Library。它简直就是为解决这个问题而生的。本博文将演示如何使用Design Support Library中的TextInputLayout控件。


官方API


运行效果


Implementing TextInputLayout

Import the Support Libraries

要使用TextInputLayout控件,你需要导入两个Library。第一个是appcompat-v7,它确保material style可以向后兼容。第二个是Design Support Library。

我在写这边博客的时候,support已经更新到23.2.0了,不过还是用我个人常用的23.1.1吧。虽然这个控件是在22.2.0中推出的,记得所有的Support library的版本保持一致。

在你的build.gradle文件中,添加如下依赖:

  compile 'com.android.support:appcompat-v7:23.1.1'compile 'com.android.support:design:23.1.1'

如果Gradle没有自动询问同步项目,选择build菜单中的Make module ‘app’ ,或者按Ctrl +F9。这样Android Studio 编译系统会自动获取必要的资源,然后你就能够使用需要的类了。

Design the User Interface

这个用户界面非常简单。它显示了一个“登录”文字与两个EditText元素,一个是为用户名准备的,一个是为密码准备的。布局中还包含了一个触发登陆流程的按钮。背景颜色是扁平风格的灰色。

另一个重要的细节是记得正确设置EditText的inputType属性。
第一个EditText的inputType应该设置成textEmail,
而第二个应该设置成textPassword。

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:background="#e3e3e3"android:layout_width="match_parent"android:layout_height="match_parent"android:padding="@dimen/activity_horizontal_margin"tools:context=".LoginActivity"android:orientation="vertical"><RelativeLayout
        android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.5"android:orientation="vertical"><TextView
            android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_centerInParent="true"android:gravity="center"android:text="Welcome"android:textSize="30sp"android:textColor="#333333"/></RelativeLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.5"android:orientation="vertical"><EditText
            android:id="@+id/username"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textEmailAddress"/><EditText
                android:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"/><Button
            android:id="@+id/btn"android:layout_marginTop="4dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Login"/></LinearLayout></LinearLayout>

你可能还想去掉app bar,也就是过去说的actionbar,编辑style.xml文件:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>

或者在代码中设置
因为继承的是AppCompatActivity

  supportRequestWindowFeature(Window.FEATURE_NO_TITLE);

Using TextInputLayout

TextInputLayout控件和LinearLayout完全一样,它只是一个容器。跟ScrollView一样,TextInputLayout只接受一个子元素。子元素需要是一个EditText元素。

<android.support.design.widget.TextInputLayoutandroid:id="@+id/usernameWrapper"android:layout_width="match_parent"android:layout_height="wrap_content"><EditTextandroid:id="@+id/username"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textEmailAddress"android:hint="Username"/></android.support.design.widget.TextInputLayout>

注意这里我在EditText中指定了另一个参数,hint。就如你知道的,这个属性允许你在EditText的内容为空的时候显示一个自定义的提示。一旦用户开始输入,hint会消失。这并不理想,因为用户丢失了他们输入信息的上下文提示。

有了TextInputLayout,这将不再是问题。一个单一的EditText 在输入文字的时候会隐藏hint,而被包含在TextInputLayout中的EditText则会让hint变成一个在EditText上方的浮动标签。同时还包括一个漂亮的material动画。

接下来,我们对password输入框做同样的事情。

<android.support.design.widget.TextInputLayoutandroid:id="@+id/passwordWrapper"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@id/usernameWrapper"android:layout_marginTop="4dp"><EditTextandroid:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"android:hint="Password"/></android.support.design.widget.TextInputLayout>

官方的教程说,EditText的hint会表现的跟预期一致。但是没有material动画也没有浮动标签,需要设置hint, 但是经验证,不设置,只要在xml中设置了 android:hint也是可以达到效果的。

官方使用的compile 'com.android.support:design:22.2.0'
我的工程使用的是compile 'com.android.support:design:23.1.1'

未做验证~

Setting Hints

初始化对theTextInputLayout视图的引用

 usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);

设置一个hint,使用setHint方法:

usernameWrapper.setHint("Username");
passwordWrapper.setHint("Password");

至此,你的登陆界面现在很好的遵循了material设计规范。运行项目查看你的登陆界面。


Handling Errors

TextInputLayout的另一个特色是它可以处理错误。通过验证输入,你可以防止用户输入无效的邮箱地址或者是太短的密码。如果没有验证,后台可能反馈回不正确的结果呈现给用户。对于用户来说既浪费了时间又体验不好。在发送到后台之前你应该先检查输入的正确性。

Implementing the onClick Method

首先你需要处理按钮的点击。有许多方法处理按钮的点击。其中一种就是写一个自定义的方法然后在xml中通过onClick属性指定,我喜欢setOnClickListener的方式,但这只是个人喜好。

btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// STUB}
});

我们知道当这个方法调用之后,用户不再需要键盘。不幸的是,如果你不告诉它,安卓不会自动的隐藏虚拟键盘。在onClick方法体中调用hideKeyboard。

private void hideKeyboard() {View view = getCurrentFocus();if (view != null) {((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);}
}

Validating Input

在设置错误标签之前,我们需要定义什么是错误,什么不是。我们假设用户名必须是一个邮箱地址并且我们想阻止用户输入无效的邮箱地址。

验证邮箱地址有点复杂。我们必须依赖正则表达式。如果你想也可以使用Apache Commons library。

我使用了Wikipedia 上关于邮箱验证的指导,写了如下的正则表达式。

/^[a-zA-Z0-9#_~!$&'()*+,;=:."(),:;<>@\[\]\\]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/

因为我们想验证字符串,我必须依赖Pattern和Matcher两个类。includeava.util.regex 包。实现如下的方法:

private static final String EMAIL_PATTERN = "^[a-zA-Z0-9#_~!$&'()*+,;=:.\"(),:;<>@\\[\\]\\\\]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*$";
private Pattern pattern = Pattern.compile(EMAIL_PATTERN);
private Matcher matcher;public boolean validateEmail(String email) {matcher = pattern.matcher(email);return matcher.matches();
}

密码的验证简单的多。很多组织为密码的验证采用了不同的策略,但是所有人都会限制最短长度。合理的密码应该不低于6个字符。

public boolean validatePassword(String password) {return password.length() > 5;
}

Retrieving Data 获取数据

就如我说的,TextInputLayout只是一个容器,但是和LinearLayout和ScrollView不同,你可以使用一个特殊的方法获得子元素,getEditText,不需要使用findViewById。

public void onClick(View v) {hideKeyboard();String username = usernameWrapper.getEditText().getText().toString();String password = passwordWrapper.getEditText().getText().toString();// TODO: Checks// TODO: Login
}

Showing Errors

TextInputLayout的错误处理简单快速。需要的方法是setErrorEnabled和setError。

setError设置一个红色的错误消息,显示在EditText的下面。如果传入的参数为null,错误消息将清空。并且它会改变整个EditText控件为红色。

setErrorEnabled开启错误提醒功能。这直接影响到布局的大小,增加底部padding为错误标签让出空间。在setError设置错误消息之前开启这个功能意味着在显示错误的时候布局不会变化。你可以把这两个方法结合起来验证下我所说的。

另一个有趣的事实是如果错误功能未开启但是你调用了传入非null参数的setError,那么setErrorEnabled(true)将自动被调用。

现在我们定义了什么是错误的什么是正确的,也知道了如何获取EditText中的数据以及显示可能的错误,onClick方法的实现就很简单了。

public void onClick(View v) {hideKeyboard();String username = usernameWrapper.getEditText().getText().toString();String password = passwordWrapper.getEditText().getText().toString();if (!validateEmail(username)) {usernameWrapper.setError("Not a valid email address!");} else if (!validatePassword(password)) {passwordWrapper.setError("Not a valid password!");} else {usernameWrapper.setErrorEnabled(false);passwordWrapper.setErrorEnabled(false);doLogin();}
}

我添加了一个doLogin方法,模拟登录成功

public void doLogin() {Toast.makeText(getApplicationContext(), "OK! I'm performing login.", Toast.LENGTH_SHORT).show();// TODO: login procedure; not within the scope of this tutorial.
}

Styling

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

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

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"><item name="colorAccent">#3498db</item>
</style>

Conclusion

我们看到了如何实现新的布局元素TextInputLayout,多亏有了刚刚引入的Design Support Library。

设计范例中,控件的实现需要让用户在输入的过程中不会丢失上下文信息,它是在去年跟Material Design一起被谷歌介绍的。在这之前,没有让开发者将这个控件应用到实际项目中的支持库。现在,如果你的应用有类似数据输入的地方,你终于可以完全遵循material design 了。


英文原文请访问:
creating-a-login-screen-using-textinputlayout

TextInputLayout-Android M新控件相关推荐

  1. 【转】Android M新控件之AppBarLayout,NavigationView,CoordinatorLayout,CollapsingToolbarLayout的使用...

    Android M新控件之AppBarLayout,NavigationView,CoordinatorLayout,CollapsingToolbarLayout的使用 分类: Android UI ...

  2. Android M 新控件了解学习

    Android M 新控件了解:FloatingActionButton,TextInputLayout,Snackbar,TabLayout, AppBarLayout,NavigationView ...

  3. Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

    在前不久的谷歌2015 I/O大会上,发布了Android新版本M,貌似从这个版本开始Android不在以数字命名版本了. 在这次的I/O大会上谷歌对Android并没有很大的改变,主要是修改完善之前 ...

  4. android Snackbar新控件解析

    Dialog和Toast,我们在日常的开发中一定非常熟悉,常常被用来作为Android应用内提示性信息的两种展示方式.然而Google在Design包中又提供了一种新的选择,那就是Snackbar.今 ...

  5. Android Design新控件之TextInputLayout 文本输入布局与自定义颜色简介

    Android 从5.0版本开始,新增了Android Materia Design库,让开发者高效的实现炫酷的UI效果 推荐: TextInputLayout(文本输入布局) TabLaout(选项 ...

  6. android ui新控件,android_常用UI控件_01_TextView3_点击打开新的activity

    点击textview打开新的activity (1) MainActivity.javapackage com.example.android_textview_opennewactivity; im ...

  7. 视频教程-Android Material Design 新控件-Android

    Android Material Design 新控件 刘志远,北京邮电大学硕士研究生, 北京育华志远科技有限公司创始人, 育华志远教育品牌负责人,育华志远课程体系打造者. 率领团队为互联网行业培训千 ...

  8. 【Android】Anroid5.0+新控件---酷炫标题栏的简单学习

    Android5.0+推出的新控件感觉特别酷,最近想模仿大神做个看图App出来,所以先把这些新控件用熟悉了. 新控件的介绍.使用等等网上相应的文章已经特别多了,题主也没那能力去写篇详解出来,本篇随笔记 ...

  9. 一个Demo学会用Android兼容包新控件

    2019独角兽企业重金招聘Python工程师标准>>> 前言 伟大的Google为Android推出了一系列的兼容包,最新的就是Design Support Library了,这里我 ...

  10. Android 5.0新控件——FloatingActionButton(悬浮按钮)

    Android 5.0新控件--FloatingActionButton(悬浮按钮) FloatingActionButton是5.0以后的新控件,一个悬浮按钮,之所以叫做悬浮按钮,主要是因为自带阴影 ...

最新文章

  1. mysql 自定义提示符
  2. java的守护线程与非守护线程
  3. Apache Sentry架构介绍
  4. 手机反编译java源码,再现反编译神器ShowJava,支持反编译出java源码
  5. ASP.NET 2.0 中实现模板中的数据绑定系列(2)
  6. 火遍全网的Hutool,如何使用Builder模式构建线程池
  7. 边缘AI研发落地生态挑战调研报告发布
  8. Happy Valentine's Day
  9. java测试字符串的编码_Java字符串测验
  10. 蓝桥每日真题之时间显示
  11. 大数据标签获取处理步骤_盘点大数据处理引擎
  12. Android使用AsyncTask设置请求超时的注意事项
  13. (转)60s快速分析Linux性能
  14. 征途猎魔mysql数据库_字典列表的拓展理解
  15. 【应用安全】垃圾短信电话不断?手机变卡变慢?可能是共享充电宝的锅……
  16. java日期 国际化_java中国际化的时间处理
  17. 笔记 :AVS2背景建模
  18. 把日期横杠转化为斜杠
  19. 在家也能健身(05):腹肌
  20. html音视频app制作,6款视频制作APP,让你成为短视频高手!

热门文章

  1. python split()
  2. jsp获取连接池的实时连接数_PHP进阶教程-实现一个简单的MySQL连接池
  3. 两个多精度十进制数加法程序设计_翁恺老师的程序设计入门——C语言 第四周习题...
  4. 基于文本挖掘的企业隐患排查质量分析模型
  5. Leetcode 38.外观数列 (每日一题 20210702)
  6. pyecharts 应用4: 二维散点图
  7. 生物计算论文笔记1:The construction of next-generationmatrices for compartmentalepidemic models
  8. tableau必知必会之拖拽功能失效是怎么回事
  9. Pycharm自定义包的导入
  10. 滴滴数据挖掘竞赛题目