3

Нужно сделать ввод десятичной дроби следующим образом:
в самом начале в поле ввода отображается 0.000, при вводе цифр получается следующее

ввели "3" -> 0.003     
ввели "1" -> 0.031  
ввели "6" -> 0.316  
ввели "9" -> 3.169  
ввели "0" - > 31.690 и т.д.

Да, можно свой велосипед, но хотелось бы найти красивое решение. Даже гуглить не знаю как.

1 ответ 1

3

Попробуйте это:

edittext.addTextChangedListener(new NumberTextWatcher());

class NumberTextWatcher implements TextWatcher {

        boolean mEditing;

        public NumberTextWatcher() {
            mEditing = false;
        }

        public synchronized void afterTextChanged(Editable s) {
            if (!mEditing) {
                mEditing = true;
                // Strip symbols
                String digits = s.toString().replaceAll("\\D", "");
                NumberFormat nf = NumberFormat.getNumberInstance();
                nf.setMinimumFractionDigits(3);
                try {
                    String formatted = nf.format(Double.parseDouble(digits) / 1000);
                    s.replace(0, s.length(), formatted);
                } catch (NumberFormatException nfe) {
                    s.clear();
                }
                mEditing = false;
            }
        }

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

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

Ваш ответ

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

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.