16

我需要在键入时替换 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("");
                }
            }
    });
4

2 回答 2

28

您可以根据需要更改它::

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);
   }
}
于 2012-06-02T13:55:14.157 回答
9

为了以交互方式更改文本,您需要注册一个TextWatcher. 但是尝试更改观察者内部的文本会导致对观察者的进一步调用。我的技巧是在我想更改文本时暂时删除观察者,然后立即重新注册

    mEditText.addTextChangedListener(new TextWatcher() {
        @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
        @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
        @Override public void afterTextChanged(Editable editable) {
            mEditText.removeTextChangedListener(this);
            mEditText.setText(//TODO change whatever you like here);
            mEditText.setSelection(editable.length()); //moves the pointer to end
            mEditText.addTextChangedListener(this);
        }
于 2015-11-06T16:12:00.163 回答