How to Automatically add thousand separators as number is input in EditText

后端 未结 13 2056
花落未央
花落未央 2020-11-27 05:21

Im creating a convertor application, I want to set the EditText so that when the user is inputting the number to be converted, a thousand separator (,) should be added autom

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 05:40

    You can use this method:

    myEditText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }
    
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                        String input = s.toString();
    
                        if (!input.isEmpty()) {
    
                            input = input.replace(",", "");
    
                            DecimalFormat format = new DecimalFormat("#,###,###");
                            String newPrice = format.format(Double.parseDouble(input));
    
    
                            myEditText.removeTextChangedListener(this); //To Prevent from Infinite Loop
    
                            myEditText.setText(newPrice);
                            myEditText.setSelection(newPrice.length()); //Move Cursor to end of String
    
                            myEditText.addTextChangedListener(this);
                        }
    
                    }
    
                    @Override
                    public void afterTextChanged(final Editable s) {
                    }
                });
    

    And to get original text use this:

    String input = myEditText.getText().toString();
    input = input.replace(",", "");
    

提交回复
热议问题