gpt4 book ai didi

android - 如何使用 InputFilter 实现数字分组输入掩码?

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:15 25 4
gpt4 key购买 nike

我正在使用 InputFilter 类制作一个支持数字分组的屏蔽 EditText。例如,当用户插入“12345”时,我想在 EditText 中显示“12,345”。我该如何实现?

这是我的不完整代码:

        InputFilter IF = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {

for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
if (dest.length() > 0 && dest.length() % 3 == 0)
{
return "," + source;
}
return null;
}
};
edtRadius.setFilters(new InputFilter[] { IF });

还有其他方法可以实现这种输入掩码吗?

最佳答案

这是对@vincent 回复的改进。它添加了对删除格式为 1234 5678 9190 的数字中的空格的检查,因此当尝试删除空格时,它只是将光标后退字符移动到空格之前的数字。即使插入空格,它也会将光标保持在相同的相对位置。

    mTxtCardNumber.addTextChangedListener(new TextWatcher() {

private boolean spaceDeleted;

public void onTextChanged(CharSequence s, int start, int before, int count) {
}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// check if a space was deleted
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = " ".equals(charDeleted.toString());
}

public void afterTextChanged(Editable editable) {
// disable text watcher
mTxtCardNumber.removeTextChangedListener(this);

// record cursor position as setting the text in the textview
// places the cursor at the end
int cursorPosition = mTxtCardNumber.getSelectionStart();
String withSpaces = formatText(editable);
mTxtCardNumber.setText(withSpaces);
// set the cursor at the last position + the spaces added since the
// space are always added before the cursor
mTxtCardNumber.setSelection(cursorPosition + (withSpaces.length() - editable.length()));

// if a space was deleted also deleted just move the cursor
// before the space
if (spaceDeleted) {
mTxtCardNumber.setSelection(mTxtCardNumber.getSelectionStart() - 1);
spaceDeleted = false;
}

// enable text watcher
mTxtCardNumber.addTextChangedListener(this);
}

private String formatText(CharSequence text)
{
StringBuilder formatted = new StringBuilder();
int count = 0;
for (int i = 0; i < text.length(); ++i)
{
if (Character.isDigit(text.charAt(i)))
{
if (count % 4 == 0 && count > 0)
formatted.append(" ");
formatted.append(text.charAt(i));
++count;
}
}
return formatted.toString();
}
});

关于android - 如何使用 InputFilter 实现数字分组输入掩码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7551159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com