尽量不要在Recycleview 中使用Editview,否则会有可能会引发以下问题
1、获取到的数据内容错乱
引起的原因
我们一般会使用textWatcher获取每个Item的输入项
但是在afterTextChanged中,系统会自动调用notifyDataSetChanged,引起重绘,导致position和相关的数据源就会乱序。
而每次复用item时,我们会对Editview的内容进行赋值,恢复它原来的输入内容,此时就引起了重绘
解决思路:
在进行赋值前去除Editview的textWatcher
实现代码
InputMethodManagerinputMethodManager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//edittext里的文字内容集合
SparseArrayetTextAry=newSparseArray();
TextWatchertextWatcher=newTextWatcher() {
@Override
public voidbeforeTextChanged(CharSequence s, intstart, intcount, intafter) {
}
@Override
public voidonTextChanged(CharSequence s, intstart, intbefore, intcount) {
}
@Override
public voidafterTextChanged(Editable s) {
etTextAry.put(etFocusPos,s.toString());
}
};
//edittext的焦点位置
intetFocusPos= -1;
@Override
publicClassEvaluationViewHolderonCreateViewHolder(ViewGroup parent, intviewType) {
View itemLayout = LayoutInflater.from(context).inflate(
R.layout.item_evaluation_object,parent, false);
return newClassEvaluationViewHolder(itemLayout);
}
@Override
public voidonViewRecycled(ClassEvaluationViewHolder holder) {
super.onViewRecycled(holder);
/**
* 当前holder被销毁时,把holder的TextChangedListener删除
*/
holder.evaluationEdit.removeTextChangedListener(textWatcher);
}
@Override
public voidonBindViewHolder(ClassEvaluationViewHolder holder, inti) {
final intposition = i;
finalClassEvaluationViewHolder viewHolder = (ClassEvaluationViewHolder) holder;
MyTrainingItemResponseBo.TrainingItemBo item =evaluationItems.get(position);
viewHolder.evaluationEdit.setText(etTextAry.get(position));
if(etFocusPos== position ) {
viewHolder.evaluationEdit.requestFocus();
viewHolder.evaluationEdit.setSelection(viewHolder.evaluationEdit.getText().length());
}
viewHolder.evaluationEdit.addTextChangedListener(textWatcher);
viewHolder.evaluationEdit.setOnTouchListener(newView.OnTouchListener() {
@Override
public booleanonTouch(View v,MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
etFocusPos=position;
}
return false;
}
});
}
@Override
public intgetItemCount() {
returnevaluationItems==null?0:evaluationItems.size();
}
@Override
public voidonViewDetachedFromWindow(ClassEvaluationViewHolder holder) {
super.onViewDetachedFromWindow(holder);
if(etFocusPos== holder.getAdapterPosition()) {
inputMethodManager.hideSoftInputFromWindow(((ClassEvaluationViewHolder) holder).evaluationEdit.getWindowToken(),0);
}
}