当用户在editText中输入任何金额时如何附加$?

时间:2014-05-28 11:37:28

标签: java android android-edittext

我的应用程序是用户在文本之前输入EditText中的任何数值,然后是$ append()。 任何帮助将不胜感激...非常感谢...

2 个答案:

答案 0 :(得分:3)

试试这个:

EditText editbox = (EditText)findViewById(R.id.editText1);
editbox.addTextChangedListener(new TextWatcher(){

        @Override
        public void afterTextChanged(Editable s){

            if(s.toString().length() > 0 && s.toString().charAt(0) != '$'){
                StringBuilder b = new StringBuilder(s.toString());
                b = b.reverse();
                b.append('$');
                b = b.reverse();
                editbox.setText(b);
                editbox.setSelection(editbox.getText().length());
            }



            int counter = 0;
            for (int i = 0; i < s.toString().length(); i++) {
                if (s.toString().charAt(i) == '$') {
                    counter++;
                }
            }
            if (counter > 1) {
                String str = s.toString().replace("$", "").trim();
                str = str.replaceAll("\\s+", "");
                StringBuilder b = new StringBuilder(str);
                b = b.reverse();
                b.append('$');
                b = b.reverse();
                edit.setText(b);
                edit.setSelection(edit.getText().length());
            } else {

                int spaceCount = 0;

                for (int i = 0; i < s.toString().length(); i++) {
                    if (s.toString().charAt(i) == ' ') {
                        spaceCount++;
                    }
                }
                if (spaceCount > 0) {
                    String str = s.toString().replace("$", "").trim();
                    str = str.replaceAll("\\s+", "");
                    StringBuilder b = new StringBuilder(str);
                    edit.setText(b);
                    edit.setSelection(edit.getText().length());
                }
            }


        }
    });

答案 1 :(得分:-1)

使用以下代码

ed.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // 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 afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            if(ed.getText().toString().length()>1)
            {
                ed.setText("$"+ed.getText().toString());
            }

        }
    });