我需要在键入时替换EditText内的文本:示例:如果用户按下“ A”,它将被存储到缓冲区中,而在EditText上显示“ D”(看起来就像他按下“ D”)。现在,我可以读取按下的字符,但是在et中不能显示任何字符,以避免stackoverflow:
final EditText et = (EditText) findViewById(R.id.editTexts); final TextView tv = (TextView) findViewById(R.id.textView2); et.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s){} public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() > 0) { tv.setText(s.toString().substring(s.length()-1)); et.setText(""); } } });
您可以根据需要更改它:
public class SampleActivity extends Activity { TextWatcher tt = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText et = (EditText) findViewById(R.id.editText1); final TextView tv = (TextView) findViewById(R.id.textView1); tt = new TextWatcher() { public void afterTextChanged(Editable s){ et.setSelection(s.length()); } public void beforeTextChanged(CharSequence s,int start,int count, int after){} public void onTextChanged(CharSequence s, int start, int before, int count) { et.removeTextChangedListener(tt); et.setText(et.getText().toString().replace("A", "C")); et.addTextChangedListener(tt); } }; et.addTextChangedListener(tt); } }