我是新手,我已经从这里阅读了文章How to do custom ListView with colorful items' backgrounds?并且我尝试做了一些任务:我在Sqlserver中有一个表包含表的列表,每个表都有状态(0,1 ,2,3)。我的问题是如何将每种状态应用于一种颜色。这是我的代码:
try {
Statement stmt2 = conn.createStatement();
rs2 = stmt2.executeQuery(command);
ArrayList<HashMap<String, String>> data = null;
data = new ArrayList<HashMap<String, String>>();
while (rs2.next()) {
HashMap<String, String> datanum = new HashMap<String, String>();
datanum.put("A", rs2.getString(name));
datanum.put("B", rs2.getString(code));
datanum.put("C", rs2.getString("TTBan"));
// datanum.put("D", rs.getString("GiaVon"));
data.add(datanum);
}
String[] from = { "A", "C" };
int[] views = { R.id.txt_Name, R.id.txt_image_gridview};
SAD = new SimpleAdapter(this, data,
R.layout.fragment_activity_list_table, from, views)
{
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
image = (TextView)findViewById(R.id.txt_image_gridview);
View view = super.getView(position, convertView, parent);
String valueChosen = String.valueOf(gridviewTable.getItemAtPosition(position));
String[] k = valueChosen.split(", B=");
String h = k[1];
// String[] tables = h.split(",");
// table = tables[0];
// System.out.println("Ma Ban la: " + table);
String[] g = h.split(", C=");
String l = g[1];
String status = l.replace("}", "");
System.out.println("aaaaaaaaaaaaaaaaaaa " + status);
if (status == "0" || status == null) {
view.setBackgroundColor(Color.GREEN);
}if(status == "1"){
view.setBackgroundColor(Color.YELLOW);
}if(status == "2"){
view.setBackgroundColor(Color.CYAN);
}if(status == "3"){
view.setBackgroundColor(Color.RED);
}
return view;
}
}
;
} catch (Exception e) {
String err = (e.getMessage() == null) ? "Error occured" : e
.getMessage();
Log.e("Erro", err);
}
gridviewTable.setAdapter(SAD);
答案 0 :(得分:0)
我找到了解决方案,代码是正确的,但是当我使用if语句时我错了。所以我像这样编辑它,一切都很好:
替换此
if (status == "0" || status == null) {
view.setBackgroundColor(Color.GREEN);
}if(status == "1"){
view.setBackgroundColor(Color.YELLOW);
}if(status == "2"){
view.setBackgroundColor(Color.CYAN);
}if(status == "3"){
view.setBackgroundColor(Color.RED);
}
有了这个:
if (status.equals(String.valueOf(0))) {
view.setBackgroundColor(Color.RED);
} else if(status.equals(String.valueOf(1))){
view.setBackgroundColor(Color.GRAY);
}else if(status.equals(String.valueOf(2))){
view.setBackgroundColor(Color.YELLOW);
}else if(status.equals(String.valueOf(3))){
view.setBackgroundColor(Color.CYAN);
}else{
view.setBackgroundColor(Color.GREEN);
}
return view;
}