我有一个包含textedit字段的Android活动。这个想法是让用户输入一些文字"空白" (最多3个)。使用以下函数插入空白:
public void insertblank(View view){
EditText editText = (EditText) findViewById(R.id.editText1);
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = editText.getText().toString().indexOf("______",lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+="______".length();
}
}
if(count <= 2){
editText.append(" ______ ");
}else{
Toast.makeText(getBaseContext(), "Maximum of 3 blanks allowed", Toast.LENGTH_LONG).show();
}
}
我需要的是,当用户退格或编辑文本时,&#34;空白&#34;需要被视为一个角色。因此,只要在该子字符串中按下退格键,就会删除______。
更新
所以在Gabe Sechan's答案的帮助下,我几乎得到了这个工作。我在onCreate中添加了addTextChangedListener并运行以下代码。这样可以替换字符串中的所有下划线,而不仅仅是currentWord中的下划线。
txt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
Spannable textSpan = txt.getText();
final int selection = txt.getSelectionStart();
final Pattern pattern = Pattern.compile("\\w+");
final Matcher matcher = pattern.matcher(textSpan);
int end = 0;
String currentWord = null;
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
if (start <= selection && selection <= end) {
currentWord = textSpan.subSequence(start, end).toString();
if(currentWord.contains("_")){
String wholeText = txt.getText().toString();
Toast.makeText(getApplicationContext(), currentWord+"", Toast.LENGTH_SHORT).show();
wholeText = wholeText.replace(currentWord, "");
txt.setText(wholeText);
txt.setSelection(txt.getText().length());
}
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
答案 0 :(得分:1)
最好的办法是在字段上放置TextWatcher,并在afterTextChanged中查找空白的更改,并在必要时删除整个空白。