0

我对editText中的限制数有疑问。我想用户只能写 1-30 的数字。当用户想放 32 我想阻止这种可能性。我想检查用户是否将第一个数字 4 我想阻止放置更多数字。当放置第一个数字 3 时,我想阻止除 0 之外的所有数字。我该怎么做?我使用 textWatcher 来观看文本,但如何阻止键盘?

4

2 回答 2

1

试试这个方法

    InputFilter filter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                Spanned dest, int dstart, int dend) {
            int num = 0;
            try {
                num = Integer.parseInt(dest.toString()+source.toString());
                if (!(num > 0 && num <= 30)) {
                    return "";
                }
            } catch (Exception e) {
                return "";
            }

            return null;
        }
    };

    editListenPort.setFilters(new InputFilter[]{filter});
于 2013-09-18T12:30:27.387 回答
0

我做了同样的事情:

editListenPort.addTextChangedListener(new TextWatcher(){
    /** Not implemented */
    @Override
    public void afterTextChanged(Editable arg0) { }
    /** Not implemented */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    /** After text has been entered into the EditText, this updates the TextView 
     * next to it with the new value. A sanity check is performed if there is no 
     * text entered at all, upon which the listen port is set to 0. */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int numberOfChars = s.length();
        if(numberOfChars > 0){
            mOwnPort = Integer.parseInt(s.toString());
        } else if(numberOfChars <= 0){
            mOwnPort = 0;
        }
        ((TextView) findViewById(R.id.labelOwnIpData)).setText("Own IP-endpoint:\n" + mOwnIp + ":" + mOwnPort);
    }
});

通过这段代码,我检查了 EditText 的输入并更新了直接位于 EditText 旁边的 TextView。

尽管我认为如果您更新 EditText 本身或发出警告,这不是问题。

于 2013-09-18T12:19:58.903 回答