使用EditText时,有时候我们会需要监听输入的回车,以做出一些操作。 或者需要把回车变成“搜索”,“发送”或“完成”等等。
EditText 为我们提供了一个属性 imeOptions 用来替换软键盘中 enter 键的外观,如actionGo 会使外观变成“前往”。 需要同时设置
android:inputType="text"。
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionGo" android:inputType="text" />
常用的几个属性以及替换的文本外观:
| 属性 | 说明 | 对应静态变量 |
|---|---|---|
| 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);
接下来设置回车按键的监听事件
setOnEditorActionListener
et1.setOnEditorActionListener(mOnEditorActionListener); // ......
private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Log.d(TAG, "actionId: " + actionId); Log.d(TAG, "event: " + event);
return false;
}
};
如果 onEditorAction 返回 true,表示消费调这个事件。
上面的 actionId 对应的是
android.view.inputmethod.EditorInfo 中的常量。
public static final int IME_ACTION_UNSPECIFIED = 0x00000000;public static final int IME_ACTION_NONE = 0x00000001;public static final int IME_ACTION_GO = 0x00000002;public static final int IME_ACTION_SEARCH = 0x00000003;public static final int IME_ACTION_SEND = 0x00000004;public static final int IME_ACTION_NEXT = 0x00000005;public static final int IME_ACTION_DONE = 0x00000006;public static final int IME_ACTION_PREVIOUS = 0x00000007;
主要介绍 setSelection 方法。
setSelection 有:
例:假设有EditText,变量名为mEt1。
把光标移动到最前
mEt1.setSelection(0);
把光标移动到最后
mEt1.setSelection(mEt1.getText().length());
光标右移一位
mEt1.setSelection(mEt1.getSelectionEnd() + 1);
光标左移一位
mEt1.setSelection(mEt1.getSelectionEnd() - 1);
要注意的是,如果传入的index超出了text的范围,会报
java.lang.IndexOutOfBoundsException
因此在实际工程中,需要判断传入的位置是否在EditText已有内容的长度范围内。
全选当前输入的text
mEt1.setSelection(0, mEt1.getText().length());
代码中动态限制输入长度
使用TextWatcher
mQueryEt.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) { // 如果EditText中的数据不为空,且长度大于指定的最大长度
if (!TextUtils.isEmpty(s) && s.length() > 15) { // 删除指定长度之后的数据
s.delete(15, s.length() - 1);
}
}
});
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70008155/viewspace-2839262/ ,如需转载,请注明出处,否则将追究法律责任。