document.write("");

Android Adapter中组件EditText文本变化监听 addTextChangedListener

问题背景:使用适配器显示一个列表,列表中Item中有EditText,滚动时会有EditText组件内容消失

步骤:

1. 在Adapter中,添加interface

public interface OnEidtTextChangeListener {
		void xxxTextChanged(CharSequence s, int start, int before, int count);
		void getXxxEditedCount();
}

private OnEidtTextChangeListener mOnEidtTextChangeListener;

public void setOnEidtTextChangeListener(OnEidtTextChangeListener mOnEidtTextChangeListener) {
		this.mOnEidtTextChangeListener = mOnEidtTextChangeListener;
}

2. 在XXXAdapter类中 实现自定义TextWatcher,

class XXXEditTextWatcher implements TextWatcher {

		private XXXAdapter.ItemViewHolder holder;
		//传入对应的ViewHolder
		public XXXEditTextWatcher(XXXAdapter.ItemViewHolder holder) {
				this.holder = holder;
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (mOnEidtTextChangeListener != null) {
						mOnEidtTextChangeListener.xxxTextChanged(s, start, before, count);
				}
		}

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

		}

		@Override
		public void afterTextChanged(Editable editable) {
				//通过ViewHolder,获取对应控件设置的tag,tag为当前的位置,即数据的position,获取适配器的数据list改变 XXX 的内容
				int position = (Integer) holder.etXXX.getTag();
				if (mList.size() > position) {
						mList.get(position).setXXX(editable.toString());
				}
				// 获取当前显示的item的index
				if (mList.size() > 0) {
						if (mOnEidtTextChangeListener != null) {
								mOnEidtTextChangeListener.getXxxEditedCount();
						}
				}
		}
}

3. 在onBindViewHolder中,组件设定tag以便于后续获取position,

holder.etXXX.setTag(position);
holder.etXXX.setText(mList.get(position).getXxx());
holder.etXXX.addTextChangedListener(new XXXEditTextWatcher(holder));

 

posted @ 2024-06-07 09:09  人间春风意  阅读(11)  评论(0编辑  收藏  举报