这周写应用的时候遇到一个问题,就是在listview中的edittext可以输入,但不能获得到edittext中输入的文字。解决的方法是给edittext添加TextWatcher监听事件,并在其中让edittext在输入时通过调用dispatchKeyEvent()方法一直获得焦点,最后在setOnKeyListener()中获得edittext输入的文字。
示例代码如下(代码全部写在adapter中):
private boolean programmaticalTextChange = false; private KeyEvent UnknownKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN); holder.groupPwd.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { currentPwd=((EditText) v).getText().toString(); return false; } }); holder.groupPwd.addTextChangedListener(new MyTextWatcher(holder.groupPwd)); public class MyTextWatcher implements TextWatcher { private EditText editText; public MyTextWatcher(EditText editText) { this.editText = editText; } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!programmaticalTextChange) editText.dispatchKeyEvent(UnknownKey); } }
时间: 2024-10-18 10:58:53