Android: Adding decimal point to EditText field, a

2019-06-23 16:07发布

问题:

In my app, the user is able to enter a dollar amount in a text field. The thing is, I need the input to adapt to the final number as they enter the digits, without actually entering the decimal point. The best way to explain this is with an example:

Suppose the user starts off with an EditText field which contains this:

.

The user wants to enter $12.53 into the field (i.e. the digits 1,2,5,3). Then he/she starts by entering 1, and the field should look like this:

.1

Then:

.12

Next:

1.25

Finally:

12.53

So as you may notice, the decimal places itself accordingly as the numbers are inputted. Is it possible to do this as the numbers are being entered? Thanks.

回答1:

Yes, this is quite possible, even you don't have to manage "$" and decimal separately.

Below is simple EditText which is manipulated by TextWatcher :

final EditText editText = (EditText) findViewById(R.id.edt);
    editText.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) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editText == null) return;
            String inputString = editable.toString();
            editText.removeTextChangedListener(this);
            String cleanString = inputString.toString().replaceAll("[$,.]", "");
            BigDecimal bigDecimal = new BigDecimal(cleanString).setScale(2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
            String  converted = NumberFormat.getCurrencyInstance().format(bigDecimal);
            editText.setText(converted);
            editText.setSelection(converted.length());
            editText.addTextChangedListener(this);
        }
    });

And if you require to know how EditText should be created in xml, have this :

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/edt"
    android:inputType="numberDecimal"
    android:textDirection="anyRtl"
    android:gravity="right"/>

This is an old question, but perhaps, it's better to be answered:)