我在recyclerview上的单个选择项目上应用自己的逻辑。当我选择项目并滚动到最后位置并选择新项目并删除背景最后选择的项目然后显示错误
java.lang.NullPointerException:尝试从字段中读取' android.view.View android.support.v7.widget.RecyclerView $ ViewHolder.itemView'在空对象引用上
我的逻辑是:
callbacks: {
title: function(tooltipItems, data) {
return '';
},
label: function(tooltipItem, data) {
var datasetLabel = '';
var label = data.labels[tooltipItem.index];
return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
适配器类:
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(SubServicesActivity.this, recyclerViewSubServices ,new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
String selectedName = serviceLists.get(position).getServiceTitleEnglish();
RecyclerView.ViewHolder viewHolder = recyclerViewSubServices.findViewHolderForPosition(position);
FrameLayout serviceImageBackground = (FrameLayout) viewHolder.itemView.findViewById(R.id.image_back_layout);
if(!select) {
serviceImageBackground.setBackground(getResources().getDrawable(R.drawable.selection_border_tick_rec));
select = true;
selectedPosition = position;
}else{
RecyclerView.ViewHolder viewHolderselect = recyclerViewSubServices.findViewHolderForPosition(selectedPosition);
FrameLayout serviceImageSelect = (FrameLayout) viewHolderselect.itemView.findViewById(R.id.image_back_layout);
serviceImageSelect.setBackgroundColor(getResources().getColor(R.color.material_grey_200));
serviceImageBackground.setBackground(getResources().getDrawable(R.drawable.selection_border_tick_rec));
selectedPosition = position;
}
}
@Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
答案 0 :(得分:0)
我也面临同样的问题,我通过以下方式解决了问题。 我刚刚创建了用于维护所选值的模型类。所以当我们滚动" onBindViewHolder"将被调用,因此我们只需检查所选位置并设置背景。
问题是Recyclerview重新使用了视图,如果没有放置视图,则返回null。
public void onBindViewHolder( ViewHolder holder, int position) {
File file =new File(imageUrlList.get(position));
View v=null;
if(file.length()>0 ){
Glide.with(mContext).load(imageUrlList.get(position)).into(holder.imageView);
holder.imagePath=imageUrlList.get(position);
// Get the Selected Item from model class and set the background.
**ArrayList<Integer>selectedImages=GalleryHelper.getInstance().getSelectedImagePositions();
if(selectedImages!=null && selectedImages.contains(position)){
Drawable highlight=mContext.getResources().getDrawable(R.drawable.image_border);
v= holder.itemView;
v.setBackground(highlight);
}else {
v= holder.itemView;
v.setBackground(null);
}
}else{
Log.i(TAG," This file is Empty : "+imageUrlList.get(position));
}**
}