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

相关文章

Python使用Pandas对比两列数据取最大值的五种方法

《Python使用Pandas对比两列数据取最大值的五种方法》本文主要介绍使用Pandas对比两列数据取最大值的五种方法,包括使用max方法、apply方法结合lambda函数、函数、clip方法、w... 目录引言一、使用max方法二、使用apply方法结合lambda函数三、使用np.maximum函数

Qt 中集成mqtt协议的使用方法

《Qt中集成mqtt协议的使用方法》文章介绍了如何在工程中引入qmqtt库,并通过声明一个单例类来暴露订阅到的主题数据,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一,引入qmqtt 库二,使用一,引入qmqtt 库我是将整个头文件/源文件都添加到了工程中进行编译,这样 跨平台

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.