滚动RecyclerView也会更改其他数据
作者:互联网
我正在使用RecyclerView来显示项目列表.我有两个TextViews一个在另一个下面.最初将第二个TextView设置为singleline = true.现在单击项目时,我将singleline = false设置为.只需点击一下即可展开它(如ExpandableList).该代码可以正常工作,但是问题在于,随着RecyclerView使用回收项目,其他项目TextView值也被设置为singleline = false.现在如何避免这种情况?
码
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.InboxViewHolder> {
private Context context;
private List<InboxModel> listInbox;
private InboxModel currentItem;
public InboxAdapter(Context context, List<InboxModel> listInbox) {
this.context = context;
this.listInbox = listInbox;
}
@Override
public InboxViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_inbox_item, parent, false);
InboxViewHolder viewHolder = new InboxViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final InboxViewHolder holder, int position) {
currentItem = listInbox.get(position);
holder.tvHeader.setText(currentItem.header);
holder.tvMsg.setText(currentItem.msg);
holder.tvHeader.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
holder.tvMsg.setSingleLine(false);
LinearLayout.LayoutParams lp= (LinearLayout.LayoutParams) holder.tvMsg.getLayoutParams();
lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
holder.tvMsg.setLayoutParams(lp);
}
});
}
@Override
public int getItemCount() {
return listInbox.size();
}
class InboxViewHolder extends RecyclerView.ViewHolder {
private TextView tvImageHeader;
private TextView tvHeader;
private TextView tvMsg;
private TextView tvDate;
public InboxViewHolder(View itemView) {
super(itemView);
tvImageHeader = (TextView) itemView.findViewById(R.id.tv_img_header);
tvHeader = (TextView) itemView.findViewById(R.id.tv_header);
tvMsg = (TextView) itemView.findViewById(R.id.tv_msg);
tvDate = (TextView) itemView.findViewById(R.id.tv_date);
}
}
解决方法:
嗯,为此,您必须保存单击位置并在onBindViewHolder()中写入条件,如下所示
@Override
public void onBindViewHolder(final InboxViewHolder holder, int position) {
if(Postion==Mysavedposition){
holder.tvMsg.setSingleLine(false);
}else{
holder.tvMsg.setSingleLine(true);
}
currentItem = listInbox.get(position);
holder.tvHeader.setText(currentItem.header);
holder.tvMsg.setText(currentItem.msg);
holder.tvHeader.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Mysavedposition=position;
holder.tvMsg.setSingleLine(false);
LinearLayout.LayoutParams lp= (LinearLayout.LayoutParams) holder.tvMsg.getLayoutParams();
lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
holder.tvMsg.setLayoutParams(lp);
}
});
}
标签:android-recyclerview,android 来源: https://codeday.me/bug/20191119/2034942.html