text.addOnTextChanged(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 4 || s.length() == 9 || s.length() == 14) {
text.append("-");
}
}
}
由于某种原因,该代码不起作用。我把它简化为应该是它的核心。理想情况下,您会看到“1234-5678-1234-5678”作为输出,因为我最多需要16位数。我让它与text.setText(s.toString() + "-")
一起使用,然后在一个可运行的帖子中,将选择设置为s.length() + 1
,但是追加为你处理。此外,在setText
生效之前,由于setSelection
,您可以告诉光标返回到开头几毫秒。
为什么不起作用?
答案 0 :(得分:2)
xml edittext声明中的输入类型不应为" number"。用这样的数字交换inputType:
android:digits="0123456789 -."
答案 1 :(得分:1)
试试这段代码。工作正常
editText.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
if (arg2 == 0) {
if (arg0.length() == 4 || arg0.length() == 9
|| arg0.length() == 14) {
editText.append("-");
}
} else {
if (arg0.length() == 4 || arg0.length() == 9
|| arg0.length() == 14) {
editText.append("");
}
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
}
});
答案 2 :(得分:0)
text.addOnTextChanged(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 4 || s.length() == 9 || s.length() == 14) {
s.append("-");
}
}
}
答案 3 :(得分:0)
private fun setNumberChangeListener(){
var actionDelete = false
cardNumber.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
actionDelete = after == 0
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
s?.let {
when (it.length) {
4, 9, 14 -> {
if (!actionDelete)
it.append(" ")
else
it.delete(s.lastIndex, s.lastIndex+1.coerceAtMost(s.lastIndex))
}
else -> {}
}
}
}
})
}