我有一个EditText,我想用它来输入日期,我想在用户插入日期时这样做,我的应用会在EditText上自动添加' - ',所以用户只需要插入数字, 离;
user type: 21 -> device automatically 21-
user type: 01 -> device automatically 21-01-
user type: 2013 -> device automatically 21-01-2013
我试过了;
edtTxt1.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Integer textlength1 = edtTxt1.getText().length();
if (textlength1 == 2) {
edtTxt1.getText().insert(2, "-");
edtTxt1.setSelection(3);
/*I also tried this, no luck
edtTxt1.setSelection(edtTxt1.getText().length());*/
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
});
结果:
user type: 21 -> device automatically 21-
user type: 01 -> device automatically 2101-
我不能把光标放在' - '
之后EDIT 我试过@svenoaks回答,我能够把光标放在' - '之后但是这就是发生的事情:
user type: 21 -> device automatically 21-
user type: 0 -> device automatically 21-210
答案 0 :(得分:2)
edtTxt1.setText(edtTxt1.getText().insert(2, "-"));
答案 1 :(得分:1)
您知道吗:您始终可以使用DatePicker从用户那里获取日期输入。
假设你要打印dd-mm-yyyy,试试这个
if(textlength1==2||textlength1==5||textlength1==7)
edtTxt1.setText(edtTxt1.getText().insert(textlength1, "-"));
答案 2 :(得分:0)
我想你可以试试edtTxt1.setText("....")