当前位置: 移动技术网 > IT编程>移动开发>Android > Android使用TextInputLayout创建登陆页面

Android使用TextInputLayout创建登陆页面

2019年07月24日  | 移动技术网IT编程  | 我要评论

泰国电视剧爱的代价,下一站天后漫画,金拼梅

本教程中,我将再次讨论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控件。

1. 实现 textinputlayout

第一步: 创建一个新的项目

在android studio中 选择new > new project 。填入所需的信息然后创建项目。我的例子的target api是17,这是design support library支持的最小api版本。这个级别的api基本上已经支持绝大多数设备了。我把主activity命名为loginactivity,它的布局文件命名为activity_login.xml。

创建完项目之后,在主activity中把android studio自动产生的oncreateoptionsmenu 和onoptionsitemselected方法删掉。我们要创建的登陆界面不需要菜单所以删掉这些方法是ok的。记得也删掉res/menu目录中的xml 菜单文件。

第二步:导入support library

要使用textinputlayout控件,你需要导入两个library。第一个是appcompat-v7,它确保material style可以向后兼容。第二个是design support library。在你的build.gradle文件中,添加如下依赖:

  dependencies {
    compile filetree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'
  }

如果gradle没有自动询问同步项目,选择build菜单中的make module ‘app' ,或者按f9。这样android studio 编译系统会自动获取必要的资源,然后你就能够使用需要的类了。

第三步:设计用户界面

这个项目的用户界面非常简单。它显示了一个“欢迎”文字(可以很容易替换成logo什么的)与两个edittext元素,一个是为用户名准备的,一个是为密码准备的。布局中还包含了一个触发登陆流程的按钮。背景颜色是扁平风格的灰色。

另一个重要的细节是记得正确设置edittext的inputtype属性。第一个edittext的inputtype应该设置成textemail,而第二个应该设置成textpassword。下面是布局的样子:

<linearlayout xmlns: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>

第四步: 使用textinputlayout

我们总算到了本教程最有趣的部分。textinputlayout控件和linearlayout完全一样,它只是一个容器。跟scrollview一样,textinputlayout只接受一个子元素。子元素需要是一个edittext元素。

  <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: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.textinputlayout
    android:id="@+id/passwordwrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/usernamewrapper"
    android:layout_margintop="4dp">

    <edittext
      android: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动画也没有浮动标签。为什么会这样?我们还缺少一些代码。

第五步: 设置 hints

下面是setcontentview方法,初始化对thetextinputlayout视图的引用。

final textinputlayout usernamewrapper = (textinputlayout) findviewbyid(r.id.usernamewrapper);
final textinputlayout passwordwrapper = (textinputlayout) findviewbyid(r.id.passwordwrapper);

要让浮动标签动起来,你只需设置一个hint,使用sethint方法:

usernamewrapper.sethint("username");
passwordwrapper.sethint("password");

然后你就完成了。你的登陆界面现在很好的遵循了material设计规范。运行项目查看你的登陆界面。

这里写图片描述

2. 处理错误

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

第一步: 实现 onclick 方法

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

  btn.setonclicklistener(new view.onclicklistener() {
    @override
    public 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);
    }
  }

第二步: 输入验证

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

验证邮箱地址有点复杂。我们必须依赖正则表达式。如果你想也可以使用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;
  }

第三步: 获取数据

就如我说的,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
  }

第四步: 显示错误

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 = usernamewrapper.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.
  }

3. 样式

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

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

 <style name="apptheme" parent="theme.a
  <style name="apptheme" parent="theme.appcompat.light.noactionbar">
    <item name="coloraccent">#3498db</item>
  </style>

总结

本教程中,我们看到了如何实现新的布局元素textinputlayout,多亏有了刚刚引入的design support library。

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网