I have a custom ListView in which I want to alternate the colors of the rows, one white, one gray, and so on. I have tried taking the remainder of the division, but the list starts at zero, so it gives me two in a row of the same color.
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
TextView tv1, tv2, tv3,tv4,tv5,tv6,tv7;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.recycler_view_item, viewGroup, false);
double residuo = position/2;
if (residuo==0){
v.setBackgroundColor(Color.GRAY);
}
return v;
}
You can use the arithmetic operator
%
, called the modulus operator. The modulus operator returns the remainder of the integer division.How does the % operator work?
If you want to paint the cell when the variable value
position
is odd (1,3,5,7,9,11...), you can use:if you want to paint the cell when the values are 0 or even (0,2,4,6,8,10...), you can use:
You can use the Mod(%) operation
I refer to an answer on the Stackoverflow forum in English.
https://stackoverflow.com/questions/13109840/android-alternate-row-colors-in-listview?answertab=active#tab-top
The remainder of the odd positions will always be 1, therefore you will be able to alternate the background color of each view, obtaining its position.
In my opinion you already had the answer, what you should do is add position to 1, so it will start at 1 and not at 0. With that your problem is solved