13

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

4

7 回答 7

8

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

  1. 每次在“onTextChanged”处理程序中更改字段的数据时,光标位置都会重置为字段上的索引 0,这在键入货币值时会发生一些烦人的情况。
  2. 它使用浮点数来格式化货币值,这可能会适得其反。

对于第一个问题我还没有解决方案,对于第二个这样的代码有效:

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

    }
于 2011-03-04T09:23:49.587 回答
3

建立 Zds。

为了将光标保持在字段的末尾,请使用它。

cashAmountEdit.setTextKeepState(cashAmountBuilder.toString());
Selection.setSelection(cashAmountEdit.getText(), cashAmountBuilder.toString().length());
于 2011-03-23T22:13:12.510 回答
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 来获得正确的格式。

于 2010-12-30T16:49:26.290 回答
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());
于 2010-06-10T11:26:38.000 回答
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);
                    }

                }

            });
于 2011-02-21T21:20:36.263 回答
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;
}
于 2013-12-19T21:05:22.530 回答
0

此答案基于Zds 的答案(这又基于ninjasense 的答案),但这应该可以解决光标位置问题:

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
  • 我使用的正则表达式与其他答案不同,这使价格保持在 < 100 美元
  • 'view' 是编辑文本,'text' 是字符串内容
  • 这对我使用EditTextamaxLength为 6(即 00.00 美元)有效
于 2015-08-05T08:03:56.583 回答