EditText与TextView非常相似,它甚至与TextView共用了绝大部分XML属性和方法。EditText和TextView的最大区别在于:EditText可以接受用户输入。
EditText组件最重要的属性是inputType,该属性相当于HTML的<input.../>元素的type属性,用于EditText为指定类型的输入组件。inputType能接受的属性值非常丰富,而且随着Androd版本的升级,该属性能接受的类型还会增加。
EditText还派生了如下两个类。
- AutoCmpleteTextView:带有自动完成功能的EditText。
- ExtractEditText:它并不是UI组件,而是EditText组件的底层服务类,负责提供全屏输入法支持。
实例:用户友好的输入界面
对于一个用户友好的输入界面而言,接受用户输入的文本框你默认会提示用户如何输入;当用户把焦点切换到输入框时,输入框自动选中其中已输入的内容,避免用户删除已有内容;当用户把焦点切换到只接受电话号码的输入框时,输入法自动切换到数字键盘。
下面程序的输入界面完成了以上功能,输入界面的界面布局如下。
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<TableRow>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="用户名:"
android:textSize="16sp"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请填写登录帐号"
android:selectAllOnFocus="true"
/>
</TableRow>
<TableRow>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="密码:"
android:textSize="16sp"
/>
<!-- android:inputType="numberPassword"表明只能接收数字密码 -->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberPassword"
/>
</TableRow>
<TableRow>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="年龄:"
android:textSize="16sp"
/>
<!-- inputType="number"表明是数值输入框 -->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"
/>
</TableRow>
<TableRow>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="生日:"
android:textSize="16sp"
/>
<!-- inputType="date"表明是日期输入框 -->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="date"
/>
</TableRow>
<TableRow>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="电话号码:"
android:textSize="16sp"
/>
<!-- inputType="phone"表明是输入电话号码的输入框 -->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请填写您的电话号码"
android:selectAllOnFocus="true"
android:inputType="phone"
/>
</TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册"
/>
</TableLayout>
上面的界面布局中第一个文本框通过android:hint指定了文本框的提示信息:请填写登录账号——这是该文本框默认的提示。当用户还没输入时,该文本框内默认显示这段信息;
第二个文本框通过android:inputType="numberPassword"设置这是一个密码框,而且只能接受数字密码,用户在该文本框输入的字符会以点号代替;第三个输入框通过android:inputType="number"设置为只能接受数值的输入框;第四个输入框通过android:inputType="date"指定它是一个日期输入框;第5个输入框通过android:inputType=“phone”设置为一个电话号码输入框。
使用Activity显示上面的界面布局将可以看到如图2.19所示的界面。
图2.19 友好的输入界面