Android EditText 点击时不弹出键盘但显示光标

时间:2022-01-15 15:57:42

      使用editText.setInputType(InputType.TYPE_NULL);可以实现点击EditText时不弹出软键盘,但是4.0之后的版本点击输入框时光标不显示,需要用到一个隐藏方法,这个方法在4.0版本叫setSoftInputShownOnFocus,到4.2又改成了setShowSoftInputOnFocus(坑爹啊这是),写了个方法兼容各个版本,仅供参考。


public void hideSoftInputMethod(EditText ed){
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

int currentVersion = android.os.Build.VERSION.SDK_INT;
String methodName = null;
if(currentVersion >= 16){
// 4.2
methodName = "setShowSoftInputOnFocus";
}
else if(currentVersion >= 14){
// 4.0
methodName = "setSoftInputShownOnFocus";
}

if(methodName == null){
ed.setInputType(InputType.TYPE_NULL);
}
else{
Class<EditText> cls = EditText.class;
Method setShowSoftInputOnFocus;
try {
setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);
setShowSoftInputOnFocus.setAccessible(true);
setShowSoftInputOnFocus.invoke(ed, false);
} catch (NoSuchMethodException e) {
ed.setInputType(InputType.TYPE_NULL);
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}