我有2个字段的JSON-名称和性别。
如果性别是男性,我想将每个名字都涂成蓝色,如果是女性,我想将它们涂成粉红色。
这是我的代码
ArrayList feedList1 = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < data.length(); i++) {
HashMap<String, Object> hm;
hm = new HashMap<String, Object>();
hm.put("id", data.getJSONObject(i).getString("id").toString());
hm.put("gender", data.getJSONObject(i).getString("gender").toString());
hm.put("name", data.getJSONObject(i).getString("name").toString());
feedList1.add(hm);
SimpleAdapter adapter = new SimpleAdapter(feedList.getContext(), feedList1, R.layout.list,
new String[] {"id","name"}, new int[] { R.id.personId, R.id.personName }){
@Override
public void setViewText(TextView v, String text) {
super.setViewText(v, text);
if (v.getId() == R.id.personName) {
if (/* how to get gender of this person*/)
v.setTextColor(R.color.female);
else
v.setTextColor(R.color.male);
}
}
};
feedList.setAdapter(adapter);
feedList.setChoiceMode(feedList.CHOICE_MODE_SINGLE);
}
请告诉我如何在IF语句中添加性别。
最佳答案
如果不创建自己的自定义适配器,则无法这样做,因此可以覆盖getView。检查以下代码,并使用CustomAdapter代替SimpleAdapter
class CustomAdapter extends SimpleAdapter {
public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Map<String, Object> item = (Map<String, Object>) getItem(position);
if ("male".equals(item.get("gender").toString())) {
view.setBackgroundColor(R.color.male);
} else {
view.setBackgroundColor(R.color.female);
}
return view;
}
}
关于java - Android ListView 着色项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26979793/