Does anyone know how to programatically set the background of a list item from a String Array? I have two string arrays one is the title for the text view and the other contain
Use a custom adapter as follows:
public class MyAdapter extends ArrayAdapter {
Context context;
int layoutResourceId;
String data[] = null;
String color[] = null;
public MyAdapter(Context context, int layoutResourceId, String[] data, String[] color) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.color = color;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
StringHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new StringHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.text1);
row.setTag(holder);
}
else
{
holder = (StringHolder)row.getTag();
}
holder.txtTitle.setText(data[position]);
row.setBackgroundColor(Color.parseColor(color[position]));
return row;
}
static class StringHolder
{
TextView txtTitle;
}
}
Then set the adapter of the listView
as follows:
ArrayAdapter adapter = new MyAdapter(this, R.layout.drawer_list_item, items, colors);
menuList.setAdapter(adapter);
Update Just noticed: you also need to update the layout file. It seems to be defining the id of the textview wrongly.
Here is the result: