EditText - 键入时更改文本

时间:2012-06-02 13:26:11

标签: java android

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

3 个答案:

答案 0 :(得分:26)

您可以根据需要进行更改::

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);
   }
}

答案 1 :(得分:8)

要以交互方式更改文本,您需要注册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);
        }

答案 2 :(得分:2)