How to reposition cursor while editing EditText field which is formatted like US currency- Android

核能气质少年 提交于 2019-12-04 17:09:52

After exploring more on this issue, I have found the solution. Where I am calculating the cursor position. I have removed onSelectionChanged(...) method from my code and I am handling selection inafterTextChanged(...) method. In the following code I have made changes in afterTextChanged(...) :

@Override
    public void afterTextChanged(Editable editable) {

        String str = editable.toString();
        String number = str.replaceAll("[,]", "");
        if (number.equals(previousNumber) || number.isEmpty()) {
            return;
        }
        previousNumber = number;

        int startText, endText;
        startText = editText.getText().length();

        int selectionStart = editText.getSelectionStart();

        String formattedString = prefix + formatNumber(number);
        editText.removeTextChangedListener(this);
        editText.setText(formattedString);
        endText = editText.getText().length();

        int selection = (selectionStart + (endText - startText));
        editText.setSelection(selection);

        editText.addTextChangedListener(this);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!