我正在从数据库中的数据编译的数组创建一个 ListView 。 数组 1:名字数组(由名字组成) 数组2:lastname数组(由姓氏组成)
每个 ListView 行都会列出一个名称。例如,如果名字是“约瑟夫”,我希望该行的背景为绿色。我该怎么做?
这是我的代码:
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;
}
}
我对此进行了研究,并看到一些人谈论在单击或选择时更改背景颜色,但我希望它在创建时具有不同的行颜色(如果名字为“约瑟夫”)。
最佳答案
这真的很简单,只需检查名字是否是约瑟夫即可。像这样的事情:
@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;
}
关于java - 使特定 ListView 行背景不同颜色 - Android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634586/