问题
I want change my RecyclerView item background with alternating color.
Here is the method in 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();
}
}
The problem is when I touch the screen and swipe down to see more item, the item background color become out of order. It is not alternating.
Am I wrong in using this method?
Thanks!
回答1:
It is because RecyclerView
recycles your old views to create new views. When you scroll down the old views are used to create the new ones,since the backgound colour of these old views was already set when onBindViewHolder
was called, you have to specify the else condition in onBindViewHolder
which will change the colour and maintain the alternating colour order. Change your onBindViewHolder
code to this:
@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());
}
回答2:
try this
NewsModel news = mNewsList.get(getAdapterPosition());
holder.setIsRecyclable(true);
if(getAdapterPosition() % 2 == 0){
holder.listView.setBackgroundColor(0x80E0EEEE);
}else{
holder.listView.setBackgroundColor(000000); // use default color
}
来源:https://stackoverflow.com/questions/47666195/recyclerview-item-background-alternating-color-out-of-order