EditText小技巧

时间:2023-03-10 07:21:41
EditText小技巧

1.让EditText不自动获取焦点

将EditText的某个父级控件设置成

android:focusable="true"
android:focusableInTouchMode="true"

2.改变软键盘右下角确认键

设置EditText控件的imeOptions属性

<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:imeOptions="actionSearch"/>
actionNone : 回车键,按下后光标到下一行
actionGo : Go,
actionSearch : 放大镜
actionSend : Send
actionNext : Next
actionDone : Done,确定/完成,隐藏软键盘,即使不是最后一个文本输入框
有时发现设置了,但是却并没有改变。并不是上面的属型无效,而是还需要将singleLine设置为true
当设置 actionSend  或 actionSearch 等属性时,可在代码中添加相关操作
commentEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEND){
commentArticle();
return true;
}
return false;
}
});

3.能获取焦点,能编辑,但是不允许弹出软键盘

采用反射设置

    private void setHideSoftInput() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
Class<EditText> cls = EditText.class;
Method setSoftInputShownOnFocus;
setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
setSoftInputShownOnFocus.setAccessible(true);
setSoftInputShownOnFocus.invoke(numberEt, false);
} catch (Exception e) {
e.printStackTrace();
}
}

4.动态设置EditText的输入类型

数值型

etValue.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);

文本型

etValue.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME);

5.能获取焦点,不能编辑

给EditText设置下面的InputFilter

        InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
return null;
}
};