androidcolorsandroid-listfragmentsimpleadapter

Android - ListFragment SimpleAdapter change color


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;
                                }
                            }
                    );

Solution

  • 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: