Android:将小数点添加到EditText字段,并使其随输入移动 [英] Android: Adding decimal point to EditText field, and make it move with input

查看:120
本文介绍了Android:将小数点添加到EditText字段,并使其随输入移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,用户可以在文本字段中输入美元金额.关键是,当他们输入数字时,我需要输入来适应最终数字,而无需实际输入小数点.最好的解释方式是通过一个示例:

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:

假设用户从包含以下内容的EditText字段开始:

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

.

用户想要在字段中输入$ 12.53(即数字1,2,5,3).然后,他/她首先输入1,该字段应如下所示:

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

然后:

.12

下一步:

1.25

最后:

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.

推荐答案

是的,即使您不必分别管理"$"decimal,这也是有可能的.

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

下面是简单的EditText,由TextWatcher操纵:

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

如果您需要知道如何在xml中创建EditText,请执行以下操作:

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:)

这篇关于Android:将小数点添加到EditText字段,并使其随输入移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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