Skip to content

Instantly share code, notes, and snippets.

@jie-meng
Last active October 29, 2021 05:21
Show Gist options
  • Save jie-meng/b0dddb331a4f24b58230592d2e5a1560 to your computer and use it in GitHub Desktop.
Save jie-meng/b0dddb331a4f24b58230592d2e5a1560 to your computer and use it in GitHub Desktop.
Android EditText with space every 4 characters
//Util methods
public static void editTextSetContentMemorizeSelection(EditText editText, CharSequence charSequence) {
int selectionStart = editText.getSelectionStart();
int selectionEnd = editText.getSelectionEnd();
editText.setText(charSequence.toString());
if (selectionStart > charSequence.toString().length()) {
selectionStart = charSequence.toString().length();
}
if (selectionStart < 0) {
selectionStart = 0;
}
if (selectionEnd > charSequence.toString().length()) {
selectionEnd = charSequence.toString().length();
}
if (selectionEnd < 0) {
selectionEnd = 0;
}
editText.setSelection(selectionStart, selectionEnd);
}
public static String formatStrWithSpaces(CharSequence can) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < can.length(); i++) {
if (i != 0 && i % 4 == 0) {
sb.append(' ');
}
sb.append(can.charAt(i));
}
return sb.toString();
}
//main
edit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String origin = s.toString().replaceAll(" ", "");
String formatStr = formatStrWithSpaces(origin);
if (!s.toString().equals(formatStr)) {
editTextSetContentMemorizeSelection(edit, formatStr);
if (before == 0 && count == 1 && formatStr.charAt(edit.getSelectionEnd() - 1) == ' ') {
edit.setSelection(edit.getSelectionEnd() + 1);
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
@cenyaoyi
Copy link

初始粘贴非格式化字串时光标的位置有点小问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment