两个TextView的Android列表视图无法为每一行实现TextChangedListener

时间:2015-01-30 09:47:12

标签: android android-arrayadapter

我有一个包含我自己的CookPoint对象的ListView。 CookPoint具有时间和临时值,两者都可以编辑。无论我如何尝试编辑第一行中的Temp值,都会更改所有行的所有临时值。类似地,在第一行中编辑时间,并且在编辑任何其他行时,所有时间都会更改。它将更改显示的值,但不会更新和保存数据结构。

我有一个自定义ArrayAdapter,它包含两个EditText视图,并在getView方法上设置TextChangedListener。我正在为每个EditText View创建一个新的Listener对象,所以无法理解为什么我要为All rows或None获取Text Changed事件。

private class CookPointArrayAdapter extends ArrayAdapter<CookPoint> {

    private ArrayList<CookPoint> mCookPoints;

    public CookPointArrayAdapter(ArrayList<CookPoint> cookPoints) {
        super(getActivity(), 0, cookPoints);

        mCookPoints = cookPoints;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //
        if(convertView == null) {
            convertView = getActivity().getLayoutInflater().inflate(R.layout.cook_point_list_item, null);
        }

        CookPoint cp = getItem(position);

        Log.d(TAG, "getView CookPoint " + position + " Time:" + cp.getTime() + " Temp:" + cp.getTemp());

        EditText time = (EditText)convertView.findViewById(R.id.cook_point_time);
        time.setText(Integer.toString(cp.getTime()));
        time.addTextChangedListener(new CookPointTextWatcher(cp, time));

        EditText temp = (EditText)convertView.findViewById(R.id.cook_point_temp);
        temp.setText(Integer.toString(cp.getTemp()));
        temp.addTextChangedListener(new CookPointTextWatcher(cp, temp));

        return convertView;
    }

    private class CookPointTextWatcher implements TextWatcher {

        private CookPoint mCookPoint;
        private View      mView;

        private CookPointTextWatcher(CookPoint cp, View view) {
            this.mCookPoint = cp;
            this.mView = view;
        }

        @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) {
            String text = editable.toString();
            Log.d(TAG, "After Text Changed CookPoint:" + Integer.toString(mCookPoint.getIndex()) + " New Value " + text);
            int i;
            try {
                i = Integer.parseInt(text);
            } catch (Exception e) {
                Log.e(TAG, "Failed to parseInt()");
                return;
            }

            switch(mView.getId()){
            case R.id.cook_point_time:
                Log.d(TAG, "SetTime" + text);
                mCookPoint.setTime(i);
                break;
            case R.id.cook_point_temp:
                Log.d(TAG, "SetTemp");
                mCookPoint.setTemp(i);
                break;
            }
        }
    }   // private class CookPointWatcher
}   //  private class CookPointArrayAdapter

有人可以告诉我为什么会出现这种行为吗?

0 个答案:

没有答案