我有一个带TextWatcher的EditText.它应该将文本格式化为人类高度,如5’9“.但是当用户犯了错误并想删除输入错误的字符时,TextWather不允许他这样做.假设用户想删除”characther the TextWather立即加回.下面是代码.那么如何允许用户删除EditText中的文本?
private class CustomTextWatcher implements TextWatcher { private EditText mEditText; public CustomTextWatcher(EditText e) { mEditText = e; } public void beforeTextChanged(CharSequence s,int start,int count,int after) { } public void onTextChanged(CharSequence s,int before,int count) { } public void afterTextChanged(Editable s) { int count = s.length(); String str = s.toString(); if (count == 1) { str = str + "'"; } else if (count == 3) { str = str + "\""; } else if ((count > 4) && (str.charAt(str.length() - 1) != '\"')) { str = str.substring(0,str.length() - 2) + str.charAt(str.length() - 1) + "\""; } else { return; } mEditText.setText(str); mEditText.setSelection(mEditText.getText().length()); }
}
解决方法
忽略Karakuri发布的有关您的代码处于错误回调中的事实,您可以添加一个简单的修复程序,您只需要听取用户使用的密钥.
如果没有对现有代码进行任何实际测试或进一步改进,这似乎可以解决您描述的问题:
package com.example.testwatchertest; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class MainActivity extends Activity implements TextWatcher { EditText editText; boolean keyDel = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.editText); editText.addTextChangedListener(this); editText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v,int keyCode,KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL){ keyDel = true; }else{ keyDel = false; } return false; } }); } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s,int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s,int count) { if (!keyDel) { String str = s.toString(); if (count == 1) { str = str + "'"; } else if (count == 3) { str = str + "\""; } else if ((count > 4) && (str.charAt(str.length() - 1) != '\"')) { str = str.substring(0,str.length() - 2) + str.charAt(str.length() - 1) + "\""; } else { return; } editText.setText(str); editText.setSelection(editText.getText().length()); } } }