如何在Android中使用千位分隔符(,)格式化EditText输入时的格式?

12

我有一个edittext,它只能输入整数而不能输入带小数点的数字。

android:inputType="number"

我希望在打字时将数字千位分隔。例如:25,000。

我知道应该使用 TextWatcher 并且我已经使用了以下代码,但无法使其正常工作:

@Override
        public void afterTextChanged(Editable viewss) {
            String s = null;
            try {
                // The comma in the format specifier does the trick
                s = String.format("%,d", Long.parseLong(viewss.toString()));
            } catch (NumberFormatException e) {
            }

        }

你能帮我做这件事吗?

3个回答

1

Adrian Cid Almageur的评论的Kotlin版本

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import java.text.DecimalFormat
import java.text.ParseException

class NumberTextWatcher(private val editText: EditText) : TextWatcher {

    private val decimalFormat = DecimalFormat("#,###.##")
    private val decimalFormatNoFrac = DecimalFormat("#,###")

    private var hasFractionalPart = false

    init {
        decimalFormat.isDecimalSeparatorAlwaysShown = true
    }

    override fun afterTextChanged(s: Editable?) {
        editText.removeTextChangedListener(this)

        try {
            val initialLength = editText.text.length

            val v = s.toString()
                .replace(decimalFormat.decimalFormatSymbols.groupingSeparator.toString(), "")
            val number = decimalFormat.parse(v)

            val cp = editText.selectionStart
            if (hasFractionalPart) {
                editText.setText(decimalFormat.format(number))
            } else {
                editText.setText(decimalFormatNoFrac.format(number))
            }
            val endLength = editText.length()
            val selection = (cp + (endLength - initialLength))
            if (selection > 0 && selection <= editText.text.length) {
                editText.setSelection(selection)
            } else {
                editText.setSelection(editText.text.length - 1)
            }
        } catch (nfe: NumberFormatException) {

        } catch (ex: ParseException) {

        }

        editText.addTextChangedListener(this)
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        hasFractionalPart =
            s.toString().contains(decimalFormat.decimalFormatSymbols.decimalSeparator)
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
}

1

将以下代码添加到您的应用程序的Gradle中: compile 'com.aldoapps:autoformatedittext:0.9.3' 在XML中添加以下命名空间: xmlns:app="http://schemas.android.com/apk/res-auto"

<com.aldoapps.autoformatedittext.AutoFormatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:isDecimal="true"
    android:maxLength="8"
    android:id="@+id/number"/>

这个库会自动添加逗号 (,) 和句号 (.)。

0
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);

使用 DecimalFormat。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接