具有固定小数的Android Money输入

时间:2010-06-10 11:09:50

标签: android format android-edittext

如何创建仅以货币格式格式化输入的edittext条目?当用户输入5时,我希望输入看起来像“$ 0.05”,当他们输入3时,输入​​现在看起来像“$ 0.53”,最后输入6,输入看起来像“$ 5.36”。

7 个答案:

答案 0 :(得分:8)

ninjasense的完整解决方案基本上有效,但它有一些问题:

  1. 每次在“onTextChanged”处理程序中更改字段的数据时,光标位置将重置为字段上的索引0,这在键入货币值时有点烦人。
  2. 它使用浮点数来格式化货币值,这可能适得其反。
  3. 对于第一个问题我还没有解决方案,对于第二个这样的代码有效:

        @Override
        public void onTextChanged(CharSequence s, int start,
                int before, int count) {
            if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
            {
                String userInput= ""+s.toString().replaceAll("[^\\d]", "");
                StringBuilder cashAmountBuilder = new StringBuilder(userInput);
    
                while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                    cashAmountBuilder.deleteCharAt(0);
                }
                while (cashAmountBuilder.length() < 3) {
                    cashAmountBuilder.insert(0, '0');
                }
                cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
                cashAmountBuilder.insert(0, '$');
    
                cashAmountEdit.setText(cashAmountBuilder.toString());
            }
    
        }
    

答案 1 :(得分:3)

建立Zds。

为了使光标位于字段的末尾,请使用此。

cashAmountEdit.setTextKeepState(cashAmountBuilder.toString());
Selection.setSelection(cashAmountEdit.getText(), cashAmountBuilder.toString().length());

答案 2 :(得分:1)

您可以使用TextWatcher来执行此类操作。

扩展TextWatcher:http://d.android.com/reference/android/text/TextWatcher.html

public class MyTextWatcher implements TextWatcher {

    public void afterTextChanged(Editable arg0) { 

    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

}

然后使用

将其添加到editText
myEditText.addTextChangedListener(new MyTextWatcher());

答案 3 :(得分:1)

我发现TextWatcher有点麻烦。相反,您可以设置键侦听器:

setKeyListener(new CalculatorKeyListener());
// Must be called after setKeyListener(), otherwise is overridden
setRawInputType(Configuration.KEYBOARD_12KEY);

然后创建一个扩展NumberKeyListener的KeyListener:

class CalculatorKeyListener extends NumberKeyListener {
    @Override
    public int getInputType() {
        return InputType.TYPE_CLASS_NUMBER;
    }

    @Override
    public boolean onKeyDown(View view, Editable content, int keyCode, KeyEvent event) {
        if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
            digitPressed(keyCode - KeyEvent.KEYCODE_0);
        } else if (keyCode == KeyEvent.KEYCODE_DEL) {                                         
            deletePressed();
        }
        return true;
    }

    @Override
    protected char[] getAcceptedChars() {
        return new char[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    }
}

然后你需要正确显示字符,但这并不困难;只需跟踪美分,然后除以或乘以10,并使用NumberFormat来确保格式正确。

答案 4 :(得分:1)

继承我的完整解决方案:

                tvValue.setRawInputType(Configuration.KEYBOARD_12KEY);

            tvValue.addTextChangedListener(new TextWatcher(){


                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    // TODO Auto-generated method stub

                    // here i converted to string
                    if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
                    {
                        String userInput= ""+s.toString().replaceAll("[^\\d]", "");
                        Float in=Float.parseFloat(userInput);
                        float percen = in/100;
                        tvValue.setText("$"+percen);
                    }

                }

            });

答案 5 :(得分:0)

我做了这个,但是没有小数,并且有里程点,请检查代码并添加支持小数的功能。

    MyEditText.addTextChangedListener(new TextWatcher() 
        {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count){
                if(s.toString().length() > 0){
                    MyEditText.removeTextChangedListener(this);                 
                    String numbers = removeCharacters(s.toString());
                    int money = 0;
                    try{
                        money = Integer.parseInt(numbers);
                    }
                    catch(Exception ex){
                        money = 0;
                    }

                    MyEditText.setText(getMoney(money));
                    //Set cursor on correct position
                    int selection = start;
                    if(count > 0){
                        selection++;
                        if(MyEditText.getText().toString().length() == 2 || MyEditText.getText().toString().length() == 6 || MyEditText.getText().toString().length() == 10){
                            selection++;
                        }                           
                    }
                    else{
                        if(MyEditText.getText().toString().length() == 4 || MyEditText.getText().toString().length() == 8){
                            selection--;
                        }
                    }

                    if(selection > MyEditText.getText().toString().length()){
                        selection = MyEditText.getText().toString().length();
                    }                       

                    MyEditText.setSelection(selection);
                    MyEditText.addTextChangedListener(this);
                }
                if(s.toString().length() == 1 && count < 1 && start == 1){
                    MyEditText.removeTextChangedListener(this);
                    MyEditText.setText("");
                    MyEditText.addTextChangedListener(this);
                }

            }           

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after){

            }           

            @Override
            public void afterTextChanged(Editable s) 
            {

            }

        });



    public String removeCharacters(String money){       

    int i=0;
    while (i<money.length())
    {
        Character c = money.charAt(i);          
            if (Character.isDigit(c) && c != '.')
            {               
                i++;
            }
            else
            {               
                money = money.replace(c.toString(), "");                
            }
    }

    return money;
}


public String getMoney(int value){
    String money = "$";
    NumberFormat numberFormatter;       
    numberFormatter = NumberFormat.getNumberInstance(Locale.GERMAN);        
    money += numberFormatter.format(value);

    return money;
}

答案 6 :(得分:0)

此答案基于Zds' answer(反过来基于ninjasense's answer),但这应解决光标位置问题:

if(!text.matches("^\\$(\\d{1,2})(\\.\\d{2})?$")) {
    int originalCursorPosition = view.getSelectionStart();
    int cursorOffset = 0;

    boolean cursorAtEnd = originalCursorPosition == text.length();

    String userInput= ""+text.replaceAll("[^\\d]", "");
    StringBuilder cashAmountBuilder = new StringBuilder(userInput);

    while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0')           {  
        cashAmountBuilder.deleteCharAt(0);
        cursorOffset--;
    }
    while (cashAmountBuilder.length() < 3) {
        cashAmountBuilder.insert(0, '0');
        cursorOffset++;
    }
    cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');
    cashAmountBuilder.insert(0, '$');

    view.setText(cashAmountBuilder.toString());
    view.setSelection(cursorAtEnd ? view.getText().length() : originalCursorPosition + cursorOffset);
}

备注:

  • 以下内容属于TextWatcher.onTextChanged
  • 我正在使用与其他答案不同的正则表达式,这使得价格保持在&lt; $ 100
  • 'view'是editText,'text'是字符串内容
  • 这对我来说很有用EditText maxLength为6(即$ 00.00)