Amrutha
Amrutha

Reputation: 575

How to create add colors to listview in android?

I am working on a listview in android and want to alternate colors to the listview?

My code:

String listview_array[] = { "1. Test1", "2. Test2" }

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    lv = (ListView) findViewById(R.id.listview);

    lv.setAdapter(new ArrayAdapter<String>(this,
            R.layout.listview_header_row, listview_array));
    lv.setTextFilterEnabled(true);
}

Any Suggestions?

Upvotes: 0

Views: 54

Answers (2)

Arun C
Arun C

Reputation: 9035

Use Custom Adapter for this

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
  private final Context context;
  private final String[] values;

  public MySimpleArrayAdapter(Context context, String[] values) {
    super(context, R.layout.rowlayout, values);
    this.context = context;
    this.values = values;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false);

    //Do assigning here Then change color

    if ((position%2)==0) {
      rowView.setBackgroundColor(R.color.first);
    } else {
      rowView.setImageResource(R.color.second);
    }

    return rowView;
  }
} 

For more about custom Adapter See this

Upvotes: 1

Sandip Lawate
Sandip Lawate

Reputation: 456

the way u set array content listview_array[] in the list view you can make array of colors and put it on background of listview . use array position for list color postion. this may solve ur problem :)

Upvotes: 0

Related Questions