我試圖動態改變的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