格式化编辑文本以采用月份和年份 [英] Format edit text to take month and year
问题描述
我有一定的要求在Android中将EditText
设置为月份和年份(因此我给出的提示为mm/yy).当用户强制输入2位数的月份时,/
应该可见,说(11/),然后是年份.
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.
以下是我在editext
上使用的代码.但是,当我按下手机键盘上的十字按钮时,它不会删除/
,而是会删除输入的月份.有人可以告诉我为什么这种行为吗?
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+"/");
}
}
});
推荐答案
要实现的目标,请尝试以下我已经测试过的
for what you want to achieve try the following i have tested it
将这两行添加到xml中的edittext
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
}
});
在此处,输入第二个数字/附加第二个数字后,编辑文本将仅包含数字,且长度不超过7.
here edit text will take only numbers and length not more than 7, when second number is entered / is appended to it
pos变量 当您位于位置3时,即/之后并按返回键,位置在2处,因此它再次附加/,以避免此pos在文本更改之前记录pos,因此当先前位置为3并按返回键时,它将不会附加/导致删除/
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 /
这篇关于格式化编辑文本以采用月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!