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+"/");
}
}
});
Try below code. it will work for you !!
In xml file :
In Java file :
You probably need to move the selection position in the control, in addition to changing the text.
for what you want to achieve try the following i have tested it
add these 2 lines to your edittext in your xml
add the following in your activity
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 /