,可以使用以下方法:
EditText editText = findViewById(R.id.edit_text);
editText.addTextChangedListener(new TextWatcher() {
private boolean isFormatting;
private String previousText;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
previousText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (isFormatting) {
return;
}
String text = s.toString();
if (!text.equals(previousText)) {
String formattedText = formatText(text); // 格式化文本,在指定位置插入斜杠
isFormatting = true;
s.replace(0, s.length(), formattedText);
isFormatting = false;
}
}
});
private String formatText(String text) {
// 假设日期格式为DDMMYYYY
if (text.length() == 2 || text.length() == 5) {
text += "/";
}
return text;
}
EditText editText = findViewById(R.id.edit_text);
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL) {
int cursorPosition = editText.getSelectionStart();
String text = editText.getText().toString();
if (cursorPosition == 3 || cursorPosition == 6) {
// 如果光标在斜杠后面,删除斜杠
editText.setText(text.substring(0, cursorPosition - 1) + text.substring(cursorPosition));
editText.setSelection(cursorPosition - 1);
return true;
}
}
return false;
}
});
这两种方法可以根据需求选择其中一种来实现在EditText的日期中添加一个斜杠。
领取专属 10元无门槛券
手把手带您无忧上云