安卓监输入框听键盘输入,设置输入框只能输入16进制字符串

 

安卓监输入框听键盘输入,设置输入框只能输入16进制字符串,支持删除、插入且不影响光标位置

安卓监输入框听键盘输入,设置输入框只能输入16进制字符串

 

 

public static void setEditTextHexInput(EditText editText) {
        editText.addTextChangedListener(
                new TextWatcher() {
                    private boolean flag = true;
                    private int index = 0;
                    private int beforeLen = 0;

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        if (flag) {
                            beforeLen = s.length();
                            index = start - count + 1;
                        }
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        flag = false;
                        String hex = toHex(s.toString());
                        if (hex.equals(s.toString())) {
                            flag = true;
                            if (beforeLen < hex.length()) {
                                index = index + hex.length() - beforeLen - 1;
                            }
                            if (index < 0) index = 0;
                            if (index > hex.length()) index = hex.length();
                            editText.setSelection(index);
                            return;
                        }
                        editText.setText(hex);
                    }
                });
    }

 

public static String toHex(String src) {
        if (isEmpty(src)) {
            return "";
        }
        src = src.replaceAll("\\s+", "").replaceAll("[^0-9a-fA-Z\\*]", "");
        char[] chars = src.toCharArray();
        StringBuilder sb = new StringBuilder();
        int i = 0, len = chars.length % 2 == 0 ? chars.length : chars.length - 1;
        for (; i < len; i++) {
            sb.append(chars[i]);
            sb.append(chars[++i]);
            sb.append(" ");
        }
        if (i < chars.length) {
            sb.append(chars[i]);
        }
        return sb.toString().trim();
    }

 

上一篇:理解Java反射


下一篇:生成三位数随机码