如何允许在edittext android的最左边位置插入一个字符

时间:2017-04-10 06:07:51

标签: android android-edittext

我已经实现了一个拨号盘,我不想让用户在edittext中插入“+”,除了edittext的左边位置。

3 个答案:

答案 0 :(得分:2)

您应该使用InputFilter来满足您的要求。试试下面的代码:

InputFilter filter = new InputFilter() {
                public CharSequence filter(CharSequence source, int start, int end,
                        Spanned dest, int dstart, int dend) {
                    for (int i = start; i < end; i++) {
                        if (source.charAt(i) == '+' && i!=start) { 
                            Toast.makeText(getApplicationContext(),"Invalid Input",Toast.LENGTH_SHORT).show();
                            return "";
                        }
                    }
                    return null;
                }

            };

editText.setFilters(new InputFilter[] { filter });

希望这有帮助。

答案 1 :(得分:0)

您可以使用TextWatcher。类似下面的代码应该达到目的:

txtNumbers.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        // Do the magic here

        int positionOfPlus = txtNumbers.getText().toString().indexOf("+");

        if (positionOfPlus != -1 && positionOfPlus != 0) {
            txtNumbers.setText("+" + txtNumbers.getText().toString().replace("+", ""));
        }
    }
});

有关TextWatcher的更多信息,请在此处阅读:TextWatcher | Android Developers

答案 2 :(得分:0)

以下是执行此操作的代码段:

editText.addTextChangedListener(new TextWatcher(){

        @Override
        public void afterTextChanged(Editable s) {}

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
            // here you can check for '+' sign, and then you can remove additional '=' sign from it.
        }
    });

希望这会对你有所帮助。