Android: adding a decimal point to an EditText field and moving with input

In my application, the user can enter the amount in the text box. The fact is that I need an input to adapt to the final number when they enter numbers, without entering a decimal point. The best way to explain this is with an example:

Suppose the user starts with an EditText field that contains the following:

.

The user wants to enter $ 12.53 in the field (i.e. the numbers 1,2,5,3). Then it starts with input 1, and the field should look like this:

0.1

Then:

.12

Further:

1.25

Finally:

12.53

Thus, as you can see, the decimal places correspond to the numbers you enter. Can this be done by entering numbers? Thanks.

+4
source share
1 answer

Yes, it’s entirely possible, even you don’t need to manage the "$" and decimal separately.

The following is just an EditText controlled by a 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 need to know how EditText should be created in xml , do the following:

 <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 maybe a better answer :)

0
source

Source: https://habr.com/ru/post/1439036/


All Articles