0

我在输入文本时尝试验证文本时遇到问题,我提示用户应该遵循“GXW-999”就是一个例子,这是我的代码:

   `public final static String[] PATTERNS = {"[A-Z]{1}" , "[A-Z]{2}" , "[A-Z]{3}" , "[A-Z]{3}-", "[A-Z]{3}-[0-9]{1}", "[A-Z]{3}-[0-9]{2}", "[A-Z]{3}-[0-9]{3}" };`
  ....
  ` mTextPreference.getEditText().setHint("GXW-999");
    mTextPreference.getEditText().setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
    mTextPreference.getEditText().addTextChangedListener(new AfterTextChanged(etext){

        @Override
        public void validate(EditText v, Editable s) {
            // TODO Auto-generated method stub
            Log.i(TAG, "after text change " + s.toString());
            String text = s.toString();
            int length = text.length();
            if(length <= 0) return;
            if(!Pattern.matches(PATTERNS[length - 1], text)){
                text = s.delete(length - 1, length).toString();
                v.setText(text);
            }
        }

    });`

我的抽象文本观察者

`private abstract class AfterTextChanged implements TextWatcher{

    private EditText v;
    public AfterTextChanged(EditText v){
        this.v = v;
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        validate(v , s);
    }

    public abstract void validate(EditText v , Editable s);

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

    }

}`

我遇到的问题是在输入最后一个数字时999,如果我超过 1 个数字,我会9999收到错误,而GXW如果我超过 1 个字符,它不会有任何错误。

我希望我的问题简洁易懂。我请求帮助,因为在我读完这篇文章后我实际上不知道其他方法,它说你无法在 EditTExtPreference 中获得确定按钮。

如果这不起作用,还有其他解决方法吗?

4

1 回答 1

0

大声笑我是菜鸟,我明白了.. 只是改变我的

        @Override
        public void validate(EditText v, Editable s) {
            // TODO Auto-generated method stub
            Log.i(TAG, "after text change " + s.toString());
            String text = s.toString();
            int length = text.length();
            if(length <= 0) return;
            if(!Pattern.matches(PATTERNS[length - 1], text)){
                text = s.delete(length - 1, length).toString();
                v.setText(text);
            }
        }

        @Override
        public void validate(EditText v, Editable s) {
            // TODO Auto-generated method stub
            Log.i(TAG, "after text change " + s.toString());
            String text = s.toString();
            int length = text.length();
            if(length <= 0) return;
            int max_length = Math.min(length - 1, PATTERNS.length - 1);
            if(!Pattern.matches(PATTERNS[max_length], text)){
                text = s.delete(length - 1, length).toString();
                Log.i(TAG, "the text " + text);
                v.setText(text);
            }
        }

及其工作..

于 2014-08-14T03:14:16.267 回答