gpt4 book ai didi

android - EditText - 如何将在 EditText 中键入的字符分隔成组或 block

转载 作者:太空狗 更新时间:2023-10-29 15:50:38 29 4
gpt4 key购买 nike

有没有一种方法可以在用户键入时将 EditText 中的字符分组?例如:1234 4567 7890 等等?

我有一个支持数字的编辑文本,长度为 16 个字符,我想将它们分组到单独的 block 中以获得更好的可见性。

最佳答案

    editText.addTextChangedListener(new FourDigitCardFormatWatcher(editText));

每4位加一个空格。使用下面的代码。

public class FourDigitCardFormatWatcher implements TextWatcher {

// Change this to what you want... ' ', '-' etc..
private final String space = " ";
EditText et_filed;


public FourDigitCardFormatWatcher(EditText et_filed){
this.et_filed = et_filed;
}

@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) {
String initial = s.toString();
// remove all non-digits characters
String processed = initial.replaceAll("\\D", "");

if (processed.length() > 4){
processed = processed.replaceAll("(\\d{4})(?=\\d)", "$1 ");
}

//Remove the listener
et_filed.removeTextChangedListener(this);

//Assign processed text
et_filed.setText(processed);

try {
et_filed.setSelection(processed.length());
} catch (Exception e) {
// TODO: handle exception
}

//Give back the listener
et_filed.addTextChangedListener(this);
}
}

关于android - EditText - 如何将在 EditText 中键入的字符分隔成组或 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43044509/

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