我试图动态改变的backgroundColor在ListView的一部分,我有例子,当我试图用一个可扩展列表视图复制它的另一部分工作在ListView罚款它失败改变列表视图(可扩展列表视图)的backgroundColor
这段代码的作品,如果一个学生是否在线
显示不同的颜色...
map.put(KEY_FIRSTNAME, temp.firstName);
map.put(KEY_NAME, temp.name);
map.put(KEY_EMAIL, temp.email);
map.put(KEY_ISONLINE, temp.isOnLine);
// change image if student is online or not
Log.d("demo", "is on line= " + temp.isOnLine);
if (temp.isOnLine.equalsIgnoreCase("1")) {
map.put(KEY_IMAGE_ISONLINE, R.color.greenColor);
} else {
map.put(KEY_IMAGE_ISONLINE, R.color.greyColor);
}
listItem.add(map);
}
myListView = (ListView) findViewById(R.id.listViewTabLeerlingen);
SimpleAdapter adapter = new SimpleAdapter(StudentTab.this,
listItem,
R.layout.list_item_student,
new String[] { KEY_FIRSTNAME, KEY_NAME,
KEY_IMAGE_ISONLINE }, new int[] {
R.id.firstNameTextView,
R.id.lastNameTextView,
R.id.logo });
myListView.setAdapter(adapter);
与它一起去的XML
<ImageView
android:id="@+id/logo"
android:layout_width="85dp"
android:layout_height="match_parent"
android:background="@color/greenColor"
android:contentDescription="Image if student is online or not"
android:src="@drawable/transparent_pixel" />
上述工作正常但是下面的代码(只是部分的代码)
...
ArrayList<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
for (int i = 0; i < _data.length(); i++) {
try {
JSONArray tmp = _data.getJSONArray(i);
HashMap<String, Object> map = new HashMap<String, Object>();
// change image if student is online or not
if (tmp.getString(3).equalsIgnoreCase("0")) {
map.put(KEY_POINTS,R.color.redColor);
}else{
map.put(KEY_POINTS,R.color.greenColor);
}
map.put(KEY_QUESTIONTEXT, tmp.getString(1));
map.put(KEY_ANSWER, tmp.getString(2));
children.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
childData.add(children);
...
...
ArrayList<ArrayList<Map<String, Object>>> childData) {
SimpleExpandableListAdapter listAdapter = new SimpleExpandableListAdapter(
this, groupData, R.layout.list_item_results_students,
new String[] { KEY_FIRSTNAME, KEY_NAME, KEY_ISJUIST },
new int[] { R.id.firstnameResults, R.id.nameResults,
R.id.resultsTextView }, childData,
R.layout.list_item_results_results, new String[] {
KEY_QUESTIONTEXT, KEY_ANSWER, KEY_POINTS }, new int[] {
R.id.questionTextView, R.id.answerTextTextView, R.id.score });
ExpandableListView myListView = (ExpandableListView) findViewById(R.id.listViewTabResultaten);
myListView.setAdapter(listAdapter);
with xml:
<ImageView
android:id="@+id/score"
android:layout_width="16dp"
android:layout_height="match_parent"
android:background="@color/greenColor"
android:contentDescription="Image if student has correct answer"
android:src="@drawable/transparent_pixel" />
我会得到这个错误:
十月6日至9日:35:21.490:E/AndroidRuntime(4406):java.lang.ClassCastException:android.widget.ImageView不能转换为android.widget。 TextView
看来所有的答案都是一样的,但这个给了我一个解决方案,我只是不明白为什么simpleadapter接受imageview。谢谢 – Stofke
我设法按照您提供的网址工作。我可以根据条件设置自定义图像,但是在我的第一个示例中,我希望以背景颜色而不是图像传递。这怎么能实现? – Stofke
好吧,我自己发现它:.setBackgroundDrawable((Drawable)...很好用 – Stofke