EditText是TextView已知的直接子类,TextView的所有功能EditText都会继承过来。下面介绍EditText不同于TextView的一些重要属性。
(一)使用inputType属性为EditText简化文本内容输入
(1)实现手机输入电话号码自动弹出数字键盘。
当使用Android手机输入电话号码时只能输入数字,这个功能就是使用了文本编辑框EditText的android:inputType属性实现的。Android:inputType定义了用户期望的数据输入类型,当指定了文本编辑框的输入类型后,Android系统会在键盘上找出一个合适的数据类型,这样Android系统就会创建一个有针对性输入数据类型的输入键盘。
如下代码所示:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"/>
</RelativeLayout>
在<EditText/>标签中使用 android:inputType="phone"来制定EditText的输入数据类型只能是电话号码数字。这样当你在文本编辑框中要输入内容时,Android系统会自动弹出数字键盘。需要注意的是:EditText的inputType属性只能指定一个。
(2)实现文本编辑的自动校正
在手机上输入一个单词的第一个或第二个字母后就希望在输入法的键盘上出现要输入的那个单词,这是很多人愿意看到的效果,要实现这个效果其实很简单,需要指定EditText的android:inputType的属性值等于textAutoCorrect,也就是文本指定校正。
布局如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"/>
-->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textAutoCorrect"
/>
</RelativeLayout>
EditText标签中android:inputType=“textAutoCorrert”表示编辑输入文字是自动校正。<!-- -->中的内容是XML的注释,不会被执行,相当于Java的“//”注释。
(二)使用hint属性给EditText添加提示文字
当登录qq时,挥发想账号和密码框中都有提示文字,当我们在账号文本编辑框中输入账号时原来的文字就会消失。像这样的效果是预设文本,要实现预设文本可以使用EditText的android:hint属性完成。
布局如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"/>
<!--
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textAutoCorrect"
/>
-->
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号"/>
</RelativeLayout>
布局文件中使用android:hint=“请输入手机号”在EditText中显示最初的文字提醒。因为电话号码都是数字,所以使用android:inputType=“phone”来弹出键盘。
(三)使用图形状态资源(StateDrawable)动态改变EditText的颜色——让文字亮起来
可以使用EditText的textColor属性为文字设置固定的颜色,但这样做文字的颜色将是不可变的。要实现动态改变EditText的文字的颜色效果,可以使用图像状态资源(StateListDrawable).图形状态资源可以根据目标视图组件状态的改变而自动切换状态,这样就可以让目标视图组件的颜色发生动态的改变。
图形状态资源是res/drawable下的XML格式文件,以<selector></selector>作为根节点,其内部的子节点是<item/>标签,<item/>的作用是使用android:color指定颜色或者使用android:drawable指定图片。
编写state.xml文件的内容,代码如下:
311

被折叠的 条评论
为什么被折叠?



