我需要输入由破折号分隔的9个大写字母,例如AAA-AAA-AAA和
输入时必须格式化此输入。

提前致谢。

最佳答案

我已经找到了使用TextWatcher的解决方案。我在用着

android:inputType="textCapCharacters|textNoSuggestions"

为EditText输入类型,以便仅接收大写字母。

        txtCode = (EditText) findViewById(R.id.txtCode);

        txtCode.addTextChangedListener( new TextWatcher() {
            boolean isEdiging;
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }


            @Override
            public void afterTextChanged(Editable s) {
                if(isEdiging) return;
                isEdiging = true;
                // removing old dashes
                StringBuilder sb = new StringBuilder();
                sb.append(s.toString().replace("-", ""));

                if (sb.length()> 3)
                    sb.insert(3, "-");
                if (sb.length()> 7)
                    sb.insert(7, "-");
                if(sb.length()> 11)
                    sb.delete(11, sb.length());

                s.replace(0, s.length(), sb.toString());
                isEdiging = false;
            }
        });

10-07 20:02
查看更多