如何限制editText中的某些字符

时间:2014-09-20 08:48:41

标签: android android-edittext

请不要急于将此消息标记为"重复"。 我找不到合适的例子。 假设我想限制char" {"在editText。

让我们考虑一些代码变体。我只在模拟器上试过它们。

       editName.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            String txt=s.toString();
            int len=txt.length();
            toastDebug("len="+myIntToStr(len));
            if (len>0) {
                try {
                    int pos=txt.indexOf("{");
                    if (pos>=0) s.replace(pos,pos+1,"");
                }
                catch(Exception e) {}
            }
        }

如果我输入" {" quiickly它导致" stackOverFlow"崩溃。 假设我键入" abcd {{{{{{{"慢。对于第一个视图,它看起来没问题,没有" {"在editText中。 但是如果我键入退格键,它就不会删除" abcd"它会删除那些看不见的" {{{{{"

我尝试更改" afterTextChanged"内的editText。下面的代码再次导致stackOverflowError。

            public void afterTextChanged(Editable s) {
            String txt=s.toString();
            int len=txt.length();
            if (len>0) {
                try {
                   editName.setText(txt)
                   or
                   s.clear
                   s.append(txt)
                }
                catch(Exception e) {}
            }
        }

我键入" {"。

后,code like this的许多示例都清除了我的editText

好吧,我修改了这段代码如下:

    editName.setFilters(new InputFilter[] { filterName });

    private InputFilter filterName = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (source==null) return null;
            return source.toString().replace("{","");
    }
};

现在它有效。但是我的android:maxLength =" 25"不起作用。 可以输入任意数量的字符。

所以我很困惑如何在editText中限制简单字符。 有任何想法吗?谢谢!

5 个答案:

答案 0 :(得分:3)

您可以通过在窗口小部件上设置EditText并在下面插入逻辑来限制用户可以在TextWatcher中输入的字符:

// we are interested in this callback
@Override
public void afterTextChanged(Editable s) {
    String result = s.toString().replaceAll("\\{", "");
    if (!s.toString().equals(result)) {
         edit.setText(result); // "edit" being the EditText on which the TextWatcher was set
         edit.setSelection(result.length()); // to set the cursor at the end of the current text             
    }
}

\\是必需的(对于其他字符),因为{字符在模式中具有特殊含义。

答案 1 :(得分:1)

此处我将“ .com ”替换为“”

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.edittextdemo.MainActivity" >

    <EditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

// Java

public class MainActivity extends Activity {

    private EditText edt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt = (EditText) findViewById(R.id.edt);
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                String currentStr = s.toString().replaceAll(".com", "");
                if (!s.toString().equals(currentStr)) {
                    edt.setText(currentStr); 
                    edt.setSelection(currentStr.length());              
                }
            }
        });
    }

答案 2 :(得分:0)

您也可以xml使用它

android:digits="0,1,2,3,4,5,6,7,8,9,.,@,qwertzuiopasdfghjklyxcvbnm"

android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "

你想放在这里。

答案 3 :(得分:0)

我的假设android:maxLength实际上是InputFilter添加到您的EditText。因此,如果您想添加更多InputFilter,则必须获取InputFilter的当前EditText数组,并将其附加到您自己的InputFIlter。我这样做,这很有效。

EditText editName = (EditText) findViewById(R.id.editText1);

        InputFilter filterName = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source==null) return null;
            return source.toString().replace("{","");
        }
    };

    //Get current Input Filter from EditText
    InputFilter[] oldInputFilter = editName.getFilters();
    //Create arrays for new InputFilter
    InputFilter[] newInputFilter = new InputFilter[oldInputFilter.length+1];
    //Copy all old Input Filter to new one
    System.arraycopy(oldInputFilter, 0, newInputFilter, 0, oldInputFilter.length);
    //Add your own input filter
    newInputFilter[newInputFilter.length-1] = filterName;
    //Set the new Input Filter
    editName.setFilters(newInputFilter);

答案 4 :(得分:0)

The above correct answer only work for one EditText.
But this work for all the EditText in you XML.

        InputFilter filter = new InputFilter() { 
            boolean canEnterSpace = false;

            public CharSequence filter(CharSequence source, int start, int end,
                    Spanned dest, int dstart, int dend) {

                if(_edtUsername.getText().toString().equals(""))
                {
                    canEnterSpace = false;
                }

                StringBuilder builder = new StringBuilder();

                for (int i = start; i < end; i++) { 
                    char currentChar = source.charAt(i);

                    if (Character.isLetterOrDigit(currentChar) || currentChar == '{') {
                        builder.append(currentChar);
                        canEnterSpace = false;
                    }

                    if(Character.isWhitespace(currentChar) && canEnterSpace) {
                        builder.append(currentChar);
                    }


                }
                return builder.toString();          
            }

        };
        _edtUsername.setFilters(new InputFilter[]{filter});
        _edtFirstName.setFilters(new InputFilter[]{filter});
        _edtLastName.setFilters(new InputFilter[]{filter});

由于