2016年5月10日星期二

listview edittext addTextChangedListener. 解决监听问题

由于 getview里边 使用的缓冲机制,所以 addTextChangedListener监听到的view的item 未必是你要的效果。 解决这个问题 沿用了 外国的 大神的 回复帖子。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.user_details_list_row, parent,false);
        holder = new ViewHolder();
        holder.mCaptionTextView  = (TextView)convertView.findViewById(id.user_detail_row_caption);
        holder.mWatcher = new MutableWatcher();
        holder.mDetailEditText = (EditText)convertView.findViewById(id.user_detail_row_value);
        holder.mDetailEditText.addTextChangedListener(holder.mWatcher);
        convertView.setTag(holder);
    } else{
        holder = (ViewHolder) convertView.getTag();
    }

    holder.mCaptionTextView.setText(mUserCaptions.get(position));

    holder.mWatcher.setActive(false);
    holder.mDetailEditText.setText(mUserDetails.get(position),BufferType.EDITABLE);
    holder.mWatcher.setPosition(position);
    holder.mWatcher.setActive(true);

    return convertView;
}

static class ViewHolder{
    public TextView mCaptionTextView;
    public EditText mDetailEditText;
    public MutableWatcher mWatcher;
}

class MutableWatcher implements TextWatcher {

    private int mPosition;
    private boolean mActive;

    void setPosition(int position) {
        mPosition = position;
    }

    void setActive(boolean active) {
        mActive = active;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { }

    @Override
    public void afterTextChanged(Editable s) {
        if (mActive) {
            mUserDetails.set(mPosition, s.toString());
        }
    }
}

没有评论:

发表评论