当用户在运行时输入时,我想自动在联系人之间添加连字符。它也应该自动删除它,
喜欢904-149-0646
我正在使用此代码,
package com.cssoft.hyphen;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText edit_number;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_number=(EditText)findViewById(R.id.edit_number);
putHyphen();
}
public void putHyphen(){
edit_number.addTextChangedListener(new TextWatcher() {
@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) {
int len=find(Integer.parseInt(s.toString()));
if(len==3||len==6){
edit_number.setText(s+"-");
}
}
});
}
public int find(int num) {
int len = 0;
while (num != 0) {
num = num / 10;
len++;
}
return len;
}
}
请尽快给我解决方案。
答案 0 :(得分:0)
尝试遵循此代码..
@Override
public void afterTextChanged(Editable text) {
if (isFormatting)
return;
isFormatting = true;
// If deleting hyphen, also delete character before or after it
if (deletingHyphen && hyphenStart > 0) {
if (deletingBackward) {
if (hyphenStart - 1 < text.length()) {
text.delete(hyphenStart - 1, hyphenStart);
}
} else if (hyphenStart < text.length()) {
text.delete(hyphenStart, hyphenStart + 1);
}
}
if (text.length() == 3 || text.length() == 7) {
text.append('-');
}
isFormatting = false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (isFormatting)
return;
// Make sure user is deleting one char, without a selection
final int selStart = Selection.getSelectionStart(s);
final int selEnd = Selection.getSelectionEnd(s);
if (s.length() > 1 // Can delete another character
&& count == 1 // Deleting only one character
&& after == 0 // Deleting
&& s.charAt(start) == '-' // a hyphen
&& selStart == selEnd) { // no selection
deletingHyphen = true;
hyphenStart = start;
// Check if the user is deleting forward or backward
if (selStart == start + 1) {
deletingBackward = true;
} else {
deletingBackward = false;
}
} else {
deletingHyphen = false;
}
}