凯发真人娱乐

android material design控件学习(三)——使用textinputlayout实现酷市场登录效果 -凯发真人娱乐

2023-10-15,,

前言

前两次,我们学习了

android material design学习(一)——tablayout的用法
android material design控件学习(二)——navigationview的学习和使用

今天我们继续md控件的学习和使用。在学习之前,我们先来看一下酷市场的效果

实现这种效果的正是我们今天的主角——textinputlayout。

学习

不管学习什么,首先看它的官方文档。这是最权威,最高效的学习途径。

文档地址:http://developer.android.com/reference/android/support/design/widget/textinputlayout.html

可以看到,textinputlayout继承自linearlayout。一般将edittext和它的子类包含在内,以便用户在输入文本时,且当提示文本被隐藏时显示一个浮动的标签。

也支持通过seterrorenabled(boolean)和seterror(charsequence)方法来显示错误提示。

用法

textinputlayout使用起来非常简单,两部搞定

1.编写xml布局文件,将edittext包含在内即可。

 
            android:id="@ id/textinputlayoutname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginleft="20dp"
android:layout_marginright="20dp"
android:layout_margintop="30dp"> android:id="@ id/edittextname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_name"
android:textcolorhint="@color/colorgray"
/>

2.编写逻辑代码

本来不需要这一步的,因为这控件存在一个bug,当清空之前输错的内容后,提示错误的红色文字并不会消失。

我在google和stackoverflow上找了很久,这貌似是google的bug。可参考 https://code.google.com/p/android/issues/detail?id=190355

为了解决这个bug,就需要我们监听edittext的输入变化了,具体处理看代码。

  medittextname.addtextchangedlistener(new textwatcher() {
@override
public void beforetextchanged(charsequence s, int start, int count, int after) { } @override
public void ontextchanged(charsequence s, int start, int before, int count) { } @override
public void aftertextchanged(editable s) {
checkname(s.tostring(),false);
}
});
/**
*若用户名为空且用户是想登录,提示错误,返回false。不为空,错误设为null
*/
private boolean checkname(charsequence name,boolean islogin) {
if(textutils.isempty(name)) {
if(islogin) {
mtextinputlayoutname.seterror(getstring(r.string.error_login_empty));
return false;
}
}else{
mtextinputlayoutname.seterror(null);
}
return true;
}

实现效果:

具体代码我上传到github了,https://github.com/johntsaiandroid/coolmarket

欢迎star&fork

android material design控件学习(三)——使用textinputlayout实现酷市场登录效果的相关教程结束。

网站地图