今天接到一个功能,需要对金额修改的时候,不调用软键盘,用页面上的数字及删除自己处理,UI如下:
首先处理上面的EditText,点击的时候不能弹软键盘,但是又要显示光标,代码如下:
if (android.os.Build.VERSION.SDK_INT > 10) {//4.0以上
try {
Class cls = EditText.class;
Method setShowSoftInputOnFocus;
setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
setShowSoftInputOnFocus.setAccessible(true);
setShowSoftInputOnFocus.invoke(et, false);
} catch (Exception e) {
e.printStackTrace();
}
}
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
InputMethodManager imm = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
}
}
});
同时要在EditText得父容器添加:
android:focusable="true"
android:focusableInTouchMode="true"
处理完软键盘和光标之后,还要t获取EditTex光标位置并且插入字符或者删除字符
在光标前添加数据的代码如下:
int index = et.getSelectionStart();
Editable editable = et.getText();
editable.insert(index, "1");
删除光标钱的数据的代码如下:
int index = et.getSelectionStart();
Editable editable = et.getText();
//判断是否还有至少一个字符数据
if(index > 0){
editable.delete(index-1, index);
}