Android Money Input with fixed decimal

后端 未结 7 1237
鱼传尺愫
鱼传尺愫 2020-12-02 00:07

How do you create an edittext entry that formats input in money format only? When the user enters 5, I want the input to look like \"$0.05\" and when they then enter 3, th

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 00:20

    ninjasense's complete solution basically works, but it has some issues:

    1. Every time the data of the field is altered in the "onTextChanged" handler, cursor position resets to index 0 on the field, which is a bit annoying to happen when typing in monetary values.
    2. It uses floats for formatting monetary values, which can backfire.

    For the first problem I don't have solution yet, for the second one code like this works:

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

提交回复
热议问题