自动将字符插入EditText

时间:2016-12-14 07:43:11

标签: android android-edittext

是否可以在EditText中插入自动字符?我有addTextChangedListener方法。输入类型为numberDecimal。如果输入开始,我尝试添加0。(点)我想得到这样的结果(0.4,0.3等)。我写了这段代码,但它没有用。

 countunicoinsSell.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) {


        }

        @Override
        public void afterTextChanged(Editable s) {


            countCourse(s.toString());
        }
    });


   private void countCourse(String value) {
    if (value == null)
        return;
    if (value.startsWith(".")) {
        countunicoinsSell.append("0");
    }

}

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

这可能适合您试用!

etMobileNumber.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(!s.toString().contains("0.")){
                etMobileNumber.setText("0.");
                Selection.setSelection(etMobileNumber.getText(), etMobileNumber.getText().length());
            }
        }
    });

答案 1 :(得分:0)

希望有所帮助



private TextWatcher textWatcher = 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) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if(s.toString().startsWith(".")){
                // append with 0
                mEditText.setText("0" + mEditText.getText().toString());
                // move the cursor to the end of the string
                mEditText.setSelection(mETEmail.length());
            }
        }
    };




答案 2 :(得分:0)

if (value.startsWith(".")) {
    countunicoinsSell.setText("0"+value);
}