我想用交替的颜色更改我的RecyclerView项目背景。
这是Adapter中的方法。
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<NewsModel> mNewsList;
class ViewHolder extends RecyclerView.ViewHolder {
TextView newsNameText;
TextView newsDataText;
View listView;
public ViewHolder(View newsView) {
super(newsView);
newsNameText = (TextView) newsView.findViewById(R.id.news_Name);
newsDataText = (TextView) newsView.findViewById(R.id.news_Data);
listView = newsView;
}
}
public NewsAdapter(List<NewsModel> newsList) {
mNewsList = newsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
return holder;
}
public void setData(List<NewsModel> viewData) {
mNewsList.clear();
mNewsList.addAll(viewData);
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
NewsModel news = mNewsList.get(position);
holder.setIsRecyclable(true);
if(position % 2 == 0){
holder.listView.setBackgroundColor(0x80E0EEEE);
}
holder.newsNameText.setText(news.getName());
holder.newsDataText.setText(news.getData());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
问题是当我触摸屏幕并向下滑动以查看更多项目时,项目背景颜色变得乱序。它没有交替。
使用这种方法我错了吗?
谢谢!
答案 0 :(得分:2)
这是因为RecyclerView
会回收旧视图以创建新视图。当您向下滚动时,旧视图用于创建新视图,因为在调用onBindViewHolder
时已经设置了这些旧视图的背景颜色,您必须在onBindViewHolder
中指定else条件改变颜色并保持交替的颜色顺序。将您的onBindViewHolder
代码更改为:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
NewsModel news = mNewsList.get(position);
holder.setIsRecyclable(true);
if(position % 2 == 0){
holder.listView.setBackgroundColor(0x80E0EEEE);
}else{
holder.listview.setBackgroundColor(#FFFFFF);
}
holder.newsNameText.setText(news.getName());
holder.newsDataText.setText(news.getData());
}
答案 1 :(得分:0)
试试这个
NewsModel news = mNewsList.get(getAdapterPosition());
holder.setIsRecyclable(true);
if(getAdapterPosition() % 2 == 0){
holder.listView.setBackgroundColor(0x80E0EEEE);
}else{
holder.listView.setBackgroundColor(000000); // use default color
}