android EditText与ListView检测变化

时间:2012-06-24 20:21:17

标签: android listview android-edittext

我有一个简单的列表视图,其中包含TextView和Editview,它使用SQLITE查询中的SimpleCursorAdapter填充。我试图找出用户何时离开EditView,以便我可以做一些简单的验证并更新数据库。我已尝试过其他帖子中提出的几种方法来做到这一点,但我无法抓住这个事件。下面是我尝试过的两种不同方式。请帮忙。我将不胜感激。

    private void showClasses(Cursor cursor) {


    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.classrow, cursor, FROM, TO);

    setListAdapter(adapter);
    adapter.notifyDataSetChanged(); 

                //ATTEMPT 1     
    for (int i = 0; i < adapter.getCount(); i++){
        EditText et = (EditText) adapter.getView(i, null, null).findViewById(R.id.classpercentage);


        et.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            Log.d("TEST","In onFocusChange");

        }
    }); 

        //METHOD 2  
         et.addTextChangedListener(new TextWatcher(){ 
        public void afterTextChanged(Editable s) { 
            Log.d("TEST","In afterTextChanged");

        } 
        public void beforeTextChanged(CharSequence s, int start, int count, int after){Log.d("TEST","In beforeTextChanged");} 
        public void onTextChanged(CharSequence s, int start, int before, int count){Log.d("TEST","In onTextChanged");} 
    }); 



    }
}

我在LogCat中没有看到任何内容,调试器中的断点也没有被击中。

1 个答案:

答案 0 :(得分:0)

您从getView收到的视图未被充实到ListView,因此您的TextWatcher无法正常工作。要使其工作,您必须创建自己的适配器。例如

public class MySimpleCursorAdapter extends SimpleCursorAdapter {
    public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    }

    @Override
    public View getView(int pos, View v, ViewGroup parent) {
        v = super.getView(pos, v, parent);
        final EditText et = (EditText) v.findViewById(R.id.classpercentage);
        et.addTextChangedListener(new TextWatcher() { 
            public void afterTextChanged(Editable s) { Log.d("TEST", "In afterTextChanged"); } 
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { Log.d("TEST", "In beforeTextChanged"); } 
            public void onTextChanged(CharSequence s, int start, int before, int count) { Log.d("TEST", "In onTextChanged"); } 
        }); 
        return v;
    }
}

然后您将方法修改为此

private void showClasses(Cursor cursor) {
    SimpleCursorAdapter adapter = new MySimpleCursorAdapter(this, R.layout.classrow, cursor, FROM, TO);
    setListAdapter(adapter);
}
相关问题