Issue
I need to set background color inside onCreateViewHolder
.
So, when my position
is equal toposition % 2 == 0
then set a background Color, else to set another Color.
My background color is standard from all of my rows, that's why i thought to use it inside onCreateViewHolder
and not onBindViewHolder
. Correct me if i am wrong. The problem is that when i am using holder.getAdapterPosition
inside onCreateViewHolder
it returns '-1'
. It seems normal to me. But how can i fix that?
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.inflate_common_item, viewGroup, false);
ViewHolder holder= new ViewHolder(mView);
if(holder.getAdapterPosition % 2 ==0)
{
//Row BackgroundColor to red.
}
else
{
//Row BackgroundColor to Green.
}
return holder;
}
So when i use the code above i am getting exception that it is index out of bound. Is there any way to fix ?
Solution
According to ideal solution you should write this code in onBindViewHolder to use "getAdapterPosition".
if you want only different background Color of row in onCreateViewHolder than you can try this,This will give you one red color row and one other color row continuously.
you need to create a global variable.
boolean Manual_color = true;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.inflate_common_item, viewGroup, false);
ViewHolder holder= new ViewHolder(mView);
if(Manual_color)
{
//Row BackgroundColor to red.
Manual_color = false;
}
else
{
//Row BackgroundColor to Green.
Manual_color = true;
}
return holder;
}
Answered By - VIKAS SHARMA
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.