Reputation: 203
I am creating a listview from arrays compiled from data in my database. Array 1: firstnamearray (composed of first names) Array 2: lastnamearray (composed of last names)
Each listview row will have a name listed in it. If the first name is "Joseph", for example, I would like the background of the row to be green. How would I do this?
Here is my code:
CustomList adapter = new CustomList(getActivity(), firstnamearray, lastnamearray);
mainListView.setAdapter(adapter);
Here is my CustomList Adapter:
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] firstnamearray;
private final String[] lastnamearray;
public CustomList(Activity context,
String[] firstnamearray, String[] lastnamearray) {
super(context, R.layout.simplerow, firstnamearray);
this.context = context;
this.firstnamearray = firstnamearray;
this.lastnamearray = lastnamearray;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.simplerow, null, true);
TextView firstname = (TextView) rowView.findViewById(R.id.firstname);
TextView lastname = (TextView) rowView.findViewById(R.id.lastname);
cardnumber.setText(firstnamearray[position]);
expdate.setText(lastnamearray[position]);
return rowView;
}
}
I've researched this and seen some people talk about changing background color on click or selection, but I want it to have a different row color on creation (if first name "Joseph").
Upvotes: 0
Views: 371
Reputation: 10358
Its really simple just check if the name is Joseph. Something like this:
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.simplerow, null, true);
TextView firstname = (TextView) rowView.findViewById(R.id.firstname);
TextView lastname = (TextView) rowView.findViewById(R.id.lastname);
if(firstnamearray[position].equels("Joseph")){
//setbackground color to your desired color
rowView.setBackgroundColor(context.getResources().getColor(R.color.red));//color defined in xml
}else{
rowView.setBackgroundColor(context.getResources().getColor(R.color.white));// your default color
}
cardnumber.setText(firstnamearray[position]);
expdate.setText(lastnamearray[position]);
return rowView;
}
Upvotes: 1