1

Подскажите, как программно можно выполнить, что бы при наборе в EditText максимального количества символов заданного maxLenght клавиатура автоматически убиралась? Спасибо

EditText xKNPEditText = (EditText) findViewById(R.id.xKNP);
        avtoOffKeyPress(xKNPEditText);
......
public void avtoOffKeyPress(final EditText mEditText)
    {
        mEditText.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) {
                Log.i("MyApp", "Длина= "+mEditText.getText().toString().length());
                if(mEditText.getText().toString().length() == 5){
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

Почему то не обращается к методу????

1
  • Опишите что именно у вас не получается - как скрыть клавиатуру, как вычислять достигли ли вы предела или как выполнить действие при достижении предела.
    – ЮрийСПб
    27 янв 2018 в 21:51

1 ответ 1

4

В TextWatcher, в методе onTextChanged(), сравнивайте текущую длину введенного текста в edittext с максимально возможной длиной, как только сравняются, уберайте клавиатуру так

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Примерно так:

mEditText = findViewById(R.id.my_edit_text);

        mEditText.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) {
                if(mEditText.getText().toString().length() == 5){
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

Если есть необходимость контролирования нескольких editText, то можно создать свой TextWatcher.

Пример, вложенного класса, он располагается в классе активности.

private class GenericTextWatcher implements TextWatcher{

    private View view;
    private GenericTextWatcher(View view) {
        this.view = view;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        if( view instanceof EditText){
            EditText editText = (EditText) view;

            if(editText.getText().toString().length() == 5){
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
            }
        }

    }

    public void afterTextChanged(Editable editable) {}
}

Использование

mEditText.addTextChangedListener(new GenericTextWatcher(mEditText));
15
  • Спасибо, я ещё новичок. Можно на примере показать как связать объект EditText и TextWatcher. Спасибо.
    – user281932
    28 янв 2018 в 9:02
  • Задача такая, есть EditText, maxLenght у которого 5 надо что бы при вводе 5 символов клавиатура убиралась, а текст считывался.
    – user281932
    28 янв 2018 в 9:12
  • дополнил ответ.
    – Likhanov
    28 янв 2018 в 9:18
  • Можно посмотреть код, почему не обращается к методу.
    – user281932
    28 янв 2018 в 15:35
  • 1
    Спасибо, код работает, ошибка была у меня в программе.
    – user281932
    3 фев 2018 в 12:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.