我正在从数据库中的数据编译的数组中创建listview。 数组1:firstnamearray(由名字组成) 数组2:lastnamearray(由姓氏组成)
每个listview行都会在其中列出一个名称。例如,如果名字是“Joseph”,我希望该行的背景为绿色。我该怎么做?
这是我的代码:
CustomList adapter = new CustomList(getActivity(), firstnamearray, lastnamearray);
mainListView.setAdapter(adapter);
这是我的CustomList适配器:
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;
}
}
我研究了这个并且看到有人谈论在点击或选择时改变背景颜色,但我希望它在创作时具有不同的行颜色(如果名字“Joseph”)。
答案 0 :(得分:1)
非常简单,只需检查名称是 Joseph 。像这样:
@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;
}