我正在尝试在列表视图的一部分中动态更改背景颜色,我有一个示例,当我尝试使用可扩展列表视图将其复制到另一部分时,它在列表视图中运行良好,但它失败了
如果学生在线或不在线,这段代码可以工作并显示不同的颜色
...
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);
使用 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" />
我会收到这个错误:
06-09 10:35:21.490: E/AndroidRuntime(4406): java.lang.ClassCastException: android.widget.ImageView 不能转换为 android.widget.TextView