Question

I'm trying to paint rows int ListView depending on it's content. I have array of int - int[] State= new int[] {1,1,1,1,1,1,0,0,0,0}; And I need to paint each row in red or green color depending on value in array. Green's flag is 0, Red's flag is 1. For example: int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};

Rows with number 0-5 must be red, 5-9 must be red.

I have adapter:

public class SpecialAdapter extends SimpleAdapter {
    private int[] colors = new int[] {Color.RED, Color.GREEN };

    private int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};


    public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
        super(context, items, resource, from, to);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      View view = super.getView(position, convertView, parent);
      ///It makes my list red-green, like zebra, but I need to paint depending on flags in State
      int colorPos = position % colors.length;      
      view.setBackgroundColor(colors[colorPos]);
      return view;
    }
}

In main activity:

SpecialAdapter adapter = new SpecialAdapter(getBaseContext(), myArrList, R.layout.list_item, 
                        new String[] {"State", "Name"},

                        new int[] {R.id.text1, R.id.text2});
                 ListView lvMain = (ListView)findViewById(R.id.listView1);        
                 lvMain.setAdapter(adapter);
Was it helpful?

Solution

You should change your getView mehtod. int colorPos = position % colors.length; returns "0" or "1". So colors[colorPos] return red and green in order. Please try this;

    public class SpecialAdapter extends SimpleAdapter {
    private int[] colors = new int[] {Color.RED, Color.GREEN };

    private int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};


    public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
        super(context, items, resource, from, to);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      View view = super.getView(position, convertView, parent); 

view.setBackgroundColor(colors[State[position]]);

      return view;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top