如何在编辑EditText字段时重新定位光标,该字段的格式类似于美国货币-Android [英] How to reposition cursor while editing EditText field which is formatted like US currency- Android

查看:93
本文介绍了如何在编辑EditText字段时重新定位光标,该字段的格式类似于美国货币-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照美国货币格式来格式化编辑文本字段,其中在字段中键入数字时,假设"12345678"看起来像是"12,345,678". 为此,我使用了TextWatcher,并且在afterTextChanged(...)方法上,我正在格式化输入的文本,例如:

I am formatting edit text field as per US currency format, where while typing number in a field, let's say "12345678" it appears like "12,345,678". For this I have used TextWatcher and on afterTextChanged(...) method I am formatting the entered text like:

@Override
    public void afterTextChanged(Editable editable) {
        String str = editable.toString();
        String number = str.replaceAll("[,]", "");
        if (number.equals(previousNumber) || number.isEmpty()) {
            return;
        }
        previousNumber = number;

        DecimalFormat formatter = new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.US));

        String formattedString = formatter.format(number);
        editText.setText(formattedString);
    }

此外,我正在使用onSelectionChanged(...)回调方法,例如:

Also, I am using onSelectionChanged(...) callback method like:

 @Override
protected void onSelectionChanged(int selStart, int selEnd) {
    this.setSelection(selStart);
}

但是在这里,此"selStart"不返回数字的实际长度,因为它排除了每种货币中的,"数字. 例如:对于"12,345,678",它返回计数为8而不是10. 这就是为什么我不能将光标放在该字段的末尾.

But here this 'selStart' doesn't return the actual length of number as it excludes the number of "," in every currency. For example: for "12,345,678" it returns count as 8 instead of 10. That's why I am not able to place my cursor at the end of the field.

以下是我正在使用的自定义EditText的代码:

Following is the code of custom EditText, which I am using:

public class CurrencyEditText extends AppCompatEditText {
private static final int MAX_LENGTH = 16;
private static final int MAX_DECIMAL_DIGIT = 2;
private static String prefix = "";
private CurrencyTextWatcher currencyTextWatcher = new CurrencyTextWatcher(this, prefix);

public CurrencyEditText(Context context) {
    this(context, null);
}

public CurrencyEditText(Context context, AttributeSet attrs) {
    this(context, attrs, android.support.v7.appcompat.R.attr.editTextStyle);
}

public CurrencyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}

@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    if (focused) {
        this.addTextChangedListener(currencyTextWatcher);
    } else {
        this.removeTextChangedListener(currencyTextWatcher);
    }
    handleCaseCurrencyEmpty(focused);
}

private void handleCaseCurrencyEmpty(boolean focused) {
    if (!focused) {
        if (getText().toString().equals(prefix)) {
            setText("");
        }
    }
}

private static class CurrencyTextWatcher implements TextWatcher {
    private final EditText editText;
    DecimalFormat formatter;
    private String previousNumber;
    private String prefix;
    Context mContext;

    CurrencyTextWatcher(EditText editText, String prefix) {
        this.editText = editText;
        this.prefix = prefix;
        formatter = new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.US));
    }

    @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 editable) {
        String str = editable.toString();
        String number = str.replaceAll("[,]", "");
        if (number.equals(previousNumber) || number.isEmpty()) {
            return;
        }
        previousNumber = number;

        String formattedString = prefix + formatNumber(number);
        editText.removeTextChangedListener(this);
        editText.setText(formattedString);
        //handleSelection();
        editText.addTextChangedListener(this);
    }

    private String formatNumber(String number) {
        if (number.contains(".")) {
            return formatDecimal(number);
        }
        return formatInteger(number);
    }

    private String formatInteger(String str) {
        BigDecimal parsed = new BigDecimal(str);
        return formatter.format(parsed);
    }

    private String formatDecimal(String str) {
        if (str.equals(".")) {
            return "0.";
        }
        BigDecimal parsed = new BigDecimal(str);
        DecimalFormat formatter = new DecimalFormat("#,##0." + getDecimalPattern(str),
                new DecimalFormatSymbols(Locale.US));
        formatter.setRoundingMode(RoundingMode.DOWN);
        return formatter.format(parsed);
    }

    private String getDecimalPattern(String str) {
        int decimalCount = str.length() - str.indexOf(".") - 1;
        StringBuilder decimalPattern = new StringBuilder();
        for (int i = 0; i < decimalCount && i < MAX_DECIMAL_DIGIT; i++) {
            decimalPattern.append("0");
        }
        return decimalPattern.toString();
    }

    /*private void handleSelection() {
        if (editText.getText().length() <= MAX_LENGTH) {
            editText.setSelection(editText.getText().length());
        }
    }*/
}

@Override
protected void onSelectionChanged(int selStart, int selEnd) {
    this.setSelection(selStart);
}

}

我不想使用this.setSelection(lengthOfTheEnteredText),因为它在您编辑字段时造成了问题! onSelectionChanged(...)不考虑数字中的,"计数的原因可能是什么?

I don't want to use this.setSelection(lengthOfTheEnteredText) because it created issue when you edit the field! What could be the reason that onSelectionChanged(...) does not consider the count of "," present in number?

推荐答案

在对该问题进行了更多研究之后,我找到了解决方案.我在哪里计算光标位置.我已经从代码中删除了onSelectionChanged(...)方法,并且正在处理afterTextChanged(...)方法中的选择.在以下代码中,我在afterTextChanged(...)中进行了更改:

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);
    }

这篇关于如何在编辑EditText字段时重新定位光标,该字段的格式类似于美国货币-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆