最近在用原生的控件和布局绘制一些界面并使用,虽然这些都是Android基本知识,但是有的时候真的感觉力不从心,感觉有必要对Android常用的控件和布局做一个系统的了解。后续一个月甚至更多的时间都会围绕这个主题展开,毕竟这里面还是有不少高级控件的,我也会尽量结合应用深入的进行了解。
上一篇:TextView 下一篇:AutoCompleteTextView与MultiAutoCompleteTextView
在上一篇中,我们对TextView及其属性进行了比较完整的学习,当然还有很多没有触及到的知识点,今天我们的主题是EditText,它是 TextView的直接子类,下面我们就结合官方的文档描述展开学习:
* A user interface element for entering and modifying text. * When you define an edit text widget, you must specify the * {@link android.R.styleable#TextView_inputType} * attribute. For example, for plain text input set inputType to "text": * <p> * <pre> * <EditText * android:id="@+id/plain_text_input" * android:layout_height="wrap_content" * android:layout_width="match_parent" * android:inputType="text"/></pre>
一个用户可以编辑和修改文本的接口,当你定义一个EditText控件时,一定要给定文本输入类型属性。下面还给了一个例子
上面的文档对EditText做了一个总体的介绍,这个控件支持用户编辑和修改文本,但是一定要设置inputType属性,这个属性真的很重要,平时在使用的过程中会经常用到。那么我们首先看一下一个TextView的模样:
在使用EditText的时候,我们通常都是提供一个给用户输入信息的接口,比如别人注册一个信息,需要输入年龄,性别,电话号码,邮箱以及密码等等各种各样的信息。那我们就有一个疑问了,每一条信息的数据样式都是千差万别的,比如邮箱是有特定格式的,电话号码只能是数字且长度固定,难道这些都需要我们自己等用户把所有信息输入完成之后自己再一个一个校验吗,显然不是的,这里就需要用到它(准确说是TextView的)的一个属性android:inputType。关于text的type都是统一定义在EditorInfo,我们在EditText的setTextType接口中找到答案:
* Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} * then a soft keyboard will not be displayed for this text view.
当然我们也可以通过对控件添加键盘监听来实现。因为考虑到inputType类型较多,我们直接根据Android的Design界面推荐的来学习。
下面我们就三个一起作为一组来学习
(1)第一组:
- Plain Text:普通文本
- Password:密码
- Password(Numeric):数字密码
在开始之前,为了更好的演示,我可能会使用电脑键盘配合软键盘的方式进行,如果你的模拟器软键盘没有开启,请参照如下操作打开,电脑键盘类似:
好了,环境准备好之后,我们来看一下运行的效果:
(2)第二组:
- E-mail: