Material Design之TextInputLayout使用示例

2024-08-30 16:18

本文主要是介绍Material Design之TextInputLayout使用示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用TextInputLayout创建一个登陆界面

介绍

Google在2015的IO大会上,给我们带来了更加详细的Material Design设计规范,同时,也给我们带来了全新的Android Design Support Library,在这个support库里面,Google给我们提供了更加规范的MD设计风格的控件。最重要的是,Android Design Support Library的兼容性更广,直接可以向下兼容到Android 2.2。这不得不说是一个良心之作。

  • 使用TextInputLayout
  • 创建一个新的工程 
    在Android Studio中,从File菜单中,选择New > New project ,填入必要的信息配置并创建工程。在我的实例中使用了API 7,这个是Design Support Library支持的最低等级。这样设置,可以让你的设备尽可能运行在更多设备上,我已经把MainActivity改成LoginActivity,布局文件activity_login.xml。 
    工程设置号以后,去掉自动生成的onCreateOptionsMenu()onOptionsItemSelected (),同时删除res/menu下面对应的xml(因为用不到menu这块)。
  • 导入支持库 
    使用TextInputLayout 控件需要导入两个库,一个是appcompat-v7,保证material styles可以向下兼容。另一个是Design Support Library。 
    在项目的build.gradle文件中,添加下面的依赖(dependencies):

        dependencies {compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])compile ‘com.android.support:design:22.2.0‘compile ‘com.android.support:appcompat-v7:22.2.0‘}
    

    如果gralde没有自动要求同步(synchronize)工程,从build菜单选择Make module ‘app‘或者按F9,这样AS会自动获取必要的资源。

  • 设计UI 
    UI很简单,一个welcome的标签(后期可以很方便的替换成图片)和两个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"></textview></relativelayout></linearlayout><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><edittext android:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"></edittext><button android:id="@+id/btn"android:layout_marginTop="4dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Login"></button></linearlayout>
    

你可能还想去掉应用栏(app bar),也就是之前说的action bar,修改下style.xml就可以了

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
  • 使用TextInputLayout 
    终于到了教程中最有趣的部分了,TextInputLayout 控件表现得就像LinearLayout 一样,它是一个容器。TextInputLayout 中只能放一个子元素,和ScrollView有点类似,并且子元素必须是EditText 。

    <android .support.design.widget.TextInputLayoutandroid: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"></edittext></android>
    

注意到了么,我在EditText设置一个属性-hint。这个属性大家都很熟悉了,EditText没有输入的时候,hint会显示,当输入第一个字母上去的时候,hint就消失了。这个体验不是太好。 
感谢TextInputLayout,这个马上就不是问题了。当EditText中输入第一个字母要隐藏hint的时候,TextInputLayout中会出现一个悬浮的标签来显示这个hint,还负责一个炫酷的的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"><edittext android:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"android:hint="Password"></edittext></android>

如果现在运行程序,啥效果都木有。当然,EditText 的hint效果除外。辣么,为啥会木有动画捏?我们还缺了点代码。 
- 设置提示信息(hints) 
setContentView()下面,初始化TextInputLayout 的引用。

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 design了,运行程序,然后你会看到登录界面。 
技术分享

处理错误

TextInputLayout另一个很赞的功能是,可以处理错误情况。通过验证用户输入,你可以防止用户输入错误的邮箱,或者输入不符合规则的密码。 
有些输入验证,验证是在后台做得,产生错误后会反馈给前台,最后展示给用户。非常耗时而且用户体验差。最好的办法是在请求后台前做校验。

  • 实现onClick 方法 
    首先处理点击事件,处理点击事件的方法也有很多种,在XML中设置方法名,然后Activity完善这个方法。或者setOnClickListener。写文章的哥们儿比较喜欢后面这种。

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

    其实,当这个方法被调用以后,就不需要键盘了。但是不幸的是,Android不会自动隐藏。怎么办呢?调用下面的方法吧。

    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 来做这个事。我这里用一个维基百科里的正则表达式。

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

    为啥这么写,就不做解释了。。。。。 
    既然我们想验证一个string,我们必须依赖Pattern and Matcher,它们在java.util.regex下面。在Activity中导入它们。

    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();
    }
    

    密码验证相对简单,不同的组织有不同的验证方式。但是大都有最小长度限制。最合理的规则就是至少输入六位字符。

    public boolean validatePassword(String password) {return password.length() > 5;
    }
    
  • 接收数据 
    之前已说过,TextInputLayout只是一个容器。不像LinearLayout and ScrollView,你可以直接获取它的子元素通过特定的方法(getEditText)。根本木有必要使用findViewById。 
    如果TextInputLayout 中没有EditText,getEditText 会返回null,你得注意下NPE了。

    public void onClick(View v) {hideKeyboard();String username = usernameWrapper.getEditText().getText().toString();String password = usernameWrapper.getEditText().getText().toString();// TODO: Checks// TODO: Login
    }
    
  • 显示错误 
    TextInputLayout 错误处理简单而迅速。相关的方法有setErrorEnabledsetError。 
    setError会弹出红色的提示消息同时显示在EditText下面,如果传入的错误消息是null,之前的消息会被清除掉。这个方法还会使EditText 也变红色。 
    setErrorEnabled 是控制这个功能的。这会直接影响layout的大小。请自行脑补。。。。 
    还有一个需要注意的是,如果没有调用setErrorEnabled(true)但是调用了setError 方法并且传入了非空的消息,setErrorEnabled(true) 会被自动调用。

正确和错误情况我们已经说明了,下面就实现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();}
}

下面是空的登录方法:

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.
}
  • 修改TextInputLayout背景

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

技术分享

总结

感谢Design Support Library给我们带来了TextInputLayout。

下面的不想翻译了,好好学习,天天向上吧。

The design paradigm that this widget implements allows users to never never lose context of the information they are entering and it was actually introduced by Google last year, along with Material Design.

At that time, there was no support library giving developers the possibility to put this widget into action in their projects, until Google I/O 2015. Now, if your application expects some sort of data input, you will finally be truly material design compliant.


转载自:http://www.mamicode.com/info-detail-965904.html

这篇关于Material Design之TextInputLayout使用示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1121310

相关文章

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(

Python使用自带的base64库进行base64编码和解码

《Python使用自带的base64库进行base64编码和解码》在Python中,处理数据的编码和解码是数据传输和存储中非常普遍的需求,其中,Base64是一种常用的编码方案,本文我将详细介绍如何使... 目录引言使用python的base64库进行编码和解码编码函数解码函数Base64编码的应用场景注意