Android - ListFragment SimpleAdapter change color

31 views Asked by At

is there an easy way to change the colour of every second row

I tried this but unfortunately it is not working.

  new SimpleAdapter(Activity.this,
                                    listElements,
                                    R.layout.list,
                                    new String[]{"dt", CONTENT, TIMESTAMP},
                                    new int[]{R.drawable.dt, R.id.content, R.id.timestamp}){
                                public View getView(int position, View v, ViewGroup parent) {
                                    if (position%2 == 0) {
                                        v.setBackgroundColor(920000);
                                    } else {
                                    }
                                    return v;
                                }
                            }
                    );
2

There are 2 answers

0
Ben P. On BEST ANSWER

The code in your question is very close to correct; you have the right idea with overriding getView(), but you should change it to look like this:

public View getView(int position, View v, ViewGroup parent) {
    v = super.getView(position, v, parent);
    if (position%2 == 0) {
        v.setBackgroundColor(0xff920000);
    } else {
        v.setBackgroundColor(/* default color */);
    }
    return v;
}

The changes I've made are:

  • Include a super.getView() call to get the default behavior for further modification
  • Start your color value int literal with 0x so that it's interpreted as a hexadecimal number
  • Include the ff value for the alpha channel
  • Also set the color in the else case to avoid problems with view recycling
2
Joshua Blevins On

Yes, create a custom adapter that implements getView like this answer does.

How can I make my ArrayAdapter follow the ViewHolder pattern?

You can implement this code.

if(position % 2 == 0){ //even number
    //make a specific color
}
else if(position % 2 == 1){ //odd number
    //make a specific color
}