當我滾動回收視圖,然後向後滾動項目互換,數據被交換。我有單獨的子項目列表,沒有特定的大小。多數情況下,當我向後滾動時,子項目有重複和/或子項目交換。我已經嘗試將代碼的動態部分移至oncreateviewholder,但這沒有任何區別。Recyclerview滾動使項目更新
private LinkedHashMap<String, ArrayList<String>> messages;
private Context mContext;
int k =0;
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mSmsSender;
public LinearLayout smsContainer;
public ViewHolder(View v) {
super(v);
mSmsSender = (TextView)v.findViewById(R.id.smsSender);
smsContainer = (LinearLayout) v.findViewById(R.id.smsContainer);
}
}
public SmsAdapter(LinkedHashMap<String, ArrayList<String>> messages, Context context){
this.messages = messages;
mContext = context;
}
@Override
public SmsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sms_message, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
final String smsSender = (new ArrayList<String>(messages.keySet())).get(k);
k++;
ArrayList<String> sms = messages.get(smsSender);
for(int i =0;i<sms.size();i++){
TextView vt = new TextView(mContext);
RelativeLayout.LayoutParams lp = new RelativeLayout.
LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
vt.setLayoutParams(lp);
vt.setPadding(3,3,3,3);
vt.setText(sms.get(i));
vh.smsContainer.addView(vt);
}
return vh;
}
@Override
public void onBindViewHolder(SmsAdapter.ViewHolder holder, int position) {
final String smsSender = (new ArrayList<String>(messages.keySet())).get(position);
holder.mSmsSender.setText(smsSender);
}
@Override
public int getItemCount() {
return messages.size();
}
}
在onBindViewHolder,每次您要創建一個列表,你應該創建它一次,然後就打電話聯繫上 – lelloman
與@lelloman,新的ArrayList同意(messages.keySet( ))應該放在構造函數 –
anhtuannd
中但是仍然存在相同的問題。 –