在Android开发中,经常需要提供用户与应用交互的界面,EditText是最为常用的一种可提供交互的控件。
1、EditText中所有文字颜色的设置:
在xml布局文件中,android:textColor是设置输入文字的颜色,android:textColorHint则是设置提示语文字的颜色。
2、EditText设置软键盘的回车键的监听事件
EditText为我们提供了一个属性imeOptions用来替换软键盘中enter键的外观,如actionDone会使外观变成“完成”。
下面列出比较经常用到的几个属性以及替换的文本外观:
actionUnspecified 未指定 EditorInfo.IME_ACTION_UNSPECIFIED.
actionNone 动作 EditorInfo.IME_ACTION_NONE
actionGo 去往 EditorInfo.IME_ACTION_GO
actionSearch 搜索 EditorInfo.IME_ACTION_SEARCH
actionSend 发送 EditorInfo.IME_ACTION_SEND
actionNext 下一项 EditorInfo.IME_ACTION_NEXT
actionDone 完成 EditorInfo.IME_ACTION_DONE
设置的方法可以在布局文件中设置 android:imeOptions="actionNext" 或者在代码中 mUserEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT);
下面是在代码中重写回车事件
第一种方式:
- editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
- @Override
- public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
- if (actionId == EditorInfo.IME_ACTION_SEARCH) {
- //EditorInfo.IME_ACTION_SEARCH、EditorInfo.IME_ACTION_SEND等分别对应EditText的imeOptions属性
- //TODO回车键按下时要执行的操作
- }
- return false;
- }
- });
- editText.setOnKeyListener(new View.OnKeyListener() {
- @Override
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER&& event.getAction() == KeyEvent.ACTION_UP) {
- //TODO:回车键按下时要执行的操作
- }
- return false;
- }
- });
3、EditText几个常用的属性:
android:password="true" 这条可以让EditText显示的内容自动为星号,输入时内容会在1秒内变成*字样。
android:numeric="true" 这条可以让输入法自动变为数字输入键盘,同时仅允许0-9的数字输入
android:capitalize="abcde" 这样仅允许接受输入abcde,一般用于密码验证
android:hint="密码" 设置显示的提示信息
android:singleLine="true" 设置单行输入,这样就不会自动换行