Format edit text to take month and year

2019-07-22 00:14发布

I have a certain requirement to make a EditText in Android to take month and year(So I gave the hint as mm/yy). When user enters month compulsorily 2 digits, then a / should be visible, say(11/) followed by year.

The following is the code that I have used on editext. However when I press the cross button on keypad of mobile it does not delete the / but deletes the month entered. Can somebody tell me why is this behaviour?

ed.addTextChangedListener(new TextWatcher(){

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

    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(ed.getText().toString().matches("[0-9]") && ed.getText().toString().length()==2)  {
             month=ed.getText().toString();
            ed.setText(month+"/");  
        }
    }
});

3条回答
迷人小祖宗
2楼-- · 2019-07-22 00:48

Try below code. it will work for you !!

In xml file :

 <EditText
                    android:id="@+id/mDateEntryField"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="12sp"
                    android:inputType="date"
                    android:maxLength="5"
                    android:hint="Exp. MM/YY"/>

In Java file :

mDateEntryField.addTextChangedListener(mDateEntryWatcher);

private TextWatcher mDateEntryWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String working = s.toString();
            boolean isValid = true;
            mDateEntryField.setError(null);
            if (working.length() == 2 && before == 0) {
                if (Integer.parseInt(working) < 1 || Integer.parseInt(working) > 12) {
                    isValid = false;
                } else {
                    working += "/";
                    mDateEntryField.setText(working);
                    mDateEntryField.setSelection(working.length());
                }
            } else if (working.length() == 5 && before == 0) {
                String enteredYear = working.substring(3);

                DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits
                String formattedDate = df.format(Calendar.getInstance().getTime());
                int currentYear = Integer.parseInt(formattedDate);
                if (Integer.parseInt(enteredYear) < currentYear) {
                    isValid = false;
                }
            } else if (working.length() != 5) {
                isValid = false;
            } else
                isValid = true;

            if (!isValid) {
                mDateEntryField.setError("Enter a valid date: MM/YY");
            } else {
                mDateEntryField.setError(null);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
        }

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

    };
查看更多
爷、活的狠高调
3楼-- · 2019-07-22 00:58

You probably need to move the selection position in the control, in addition to changing the text.

查看更多
Explosion°爆炸
4楼-- · 2019-07-22 01:06

for what you want to achieve try the following i have tested it

add these 2 lines to your edittext in your xml

android:maxLength="7"
android:inputType="number"

add the following in your activity

public int pos=0; //declare this as global variable

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

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

            if(ed.getText().length()==2 && pos!=3)
            {   ed.setText(ed.getText().toString()+"/");
                ed.setSelection(3);
            }

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
            pos=ed.getText().length();
        }

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

        }
    });

here edit text will take only numbers and length not more than 7, when second number is entered / is appended to it

The pos variable when you are at position 3 ie after / and press a back key the position is at 2 so it again appends / to avoid this pos records the pos before the text changed so when previous position was 3 before you press back key it will not append / resulting in deleting /

查看更多
登录 后发表回答