【问题标题】:How to format the input of EditText when typing with thousands separators (,) in Android?在Android中使用千位分隔符(,)输入时如何格式化EditText的输入?
【发布时间】:2015-04-29 17:50:56
【问题描述】:

我有一个 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) {
            }

        }

你能帮我做吗?

【问题讨论】:

    标签: java android android-edittext number-formatting textwatcher


    【解决方案1】:

    测试这个例子:

    import java.text.DecimalFormat;
    import java.text.ParseException;
    
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.EditText;
    
    public class NumberTextWatcher implements TextWatcher {
    
        private DecimalFormat df;
        private DecimalFormat dfnd;
        private boolean hasFractionalPart;
    
        private EditText et;
    
        public NumberTextWatcher(EditText et)
        {
            df = new DecimalFormat("#,###.##");
            df.setDecimalSeparatorAlwaysShown(true);
            dfnd = new DecimalFormat("#,###");
            this.et = et;
            hasFractionalPart = false;
        }
    
        @SuppressWarnings("unused")
        private static final String TAG = "NumberTextWatcher";
    
        @Override
        public void afterTextChanged(Editable s)
        {
            et.removeTextChangedListener(this);
    
            try {
                int inilen, endlen;
                inilen = et.getText().length();
    
                String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
                Number n = df.parse(v);
                int cp = et.getSelectionStart();
                if (hasFractionalPart) {
                    et.setText(df.format(n));
                } else {
                    et.setText(dfnd.format(n));
                }
                endlen = et.getText().length();
                int sel = (cp + (endlen - inilen));
                if (sel > 0 && sel <= et.getText().length()) {
                    et.setSelection(sel);
                } else {
                    // place cursor at the end?
                    et.setSelection(et.getText().length() - 1);
                }
            } catch (NumberFormatException nfe) {
                // do nothing?
            } catch (ParseException e) {
                // do nothing?
            }
    
            et.addTextChangedListener(this);
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
            {
                hasFractionalPart = true;
            } else {
                hasFractionalPart = false;
            }
        }
    
    }
    

    要使用它,请将 TextChangedListener 添加到 EditText 组件。

    editText.addTextChangedListener(new NumberTextWatcher(editText));
    

    【讨论】:

    • 如何在文本中添加前导零?我想显示类似 0939 的文字
    • @FarshidABZ 我不知道我现在没有使用 android。
    • 谢谢@Adrian
    • 如果用户从字段中删除所有文本,这将崩溃。在设置光标位置之前需要确保 et.getText().length()>0
    【解决方案2】:

    将此添加到您应用的 Gradle 编译'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"/>
    

    这个lib自动添加(,)(.)

    【讨论】:

      【解决方案3】:
      DecimalFormat formatter = new DecimalFormat("#,###,###");
      String yourFormattedString = formatter.format(100000);
      

      使用十进制格式

      【讨论】:

        【解决方案4】:

        Adrian Cid Almageur's comment 的 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) {}
        }
        

        【讨论】:

          猜你喜欢
          • 2014-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-28
          相关资源
          最近更新 更多