禁用0和。在EditText之后 -

时间:2014-02-27 10:26:25

标签: android

我有一个带android:inputType="numberDecimal|numberSigned"的EditText有没有办法禁用0和。当我第一次进入 - ?

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方式。

if(mUname.getText().toString().contains("-")){
        if (mUname.getText().toString().contains("0") || mUname.getText().toString().contains("."))
        {
            //do your stuff
        }
        else{
            // alert
        }
    }

答案 1 :(得分:0)

是的,您可以禁用在edittext中输入0作为第一个数字。你需要做的就是

    edittext.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
             String input = editable.toString();
            if (input.length() > 0 && input.charAt(0) == '0') {
                editable.replace(0, 1, "");
                edittext.setError("Please enter valid number")
            }
        }
    });

答案 2 :(得分:0)

试试这可以阻止edittext中的任何字符

public class MainActivity extends Activity {

    private EditText editText;
    private String blockCharacterSet = "0";

    private InputFilter filter = new InputFilter() {

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

            if (source != null && blockCharacterSet.contains(("" + source))) {
                return "";
            }
            return null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.editText);

        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String input = editable.toString();
                if (input.equals("-")) {
                    editText.setFilters(new InputFilter[] { filter });
                    edittext.setError("Please enter valid number");
                }
            }
        });
        
        
    }

}

添加一个文本观察器,它将观察字符是否 - 然后它不会允许字符