我已經創建了自定義listview,每一行看起來像我的文件custom_row.xml。有什麼辦法,如何爲每一行單獨設置不同的背景顏色(我需要設置它,因爲我的行可以有不同的值)。Android - 自定義listView,每行不同顏色
感謝任何想法
我已經創建了自定義listview,每一行看起來像我的文件custom_row.xml。有什麼辦法,如何爲每一行單獨設置不同的背景顏色(我需要設置它,因爲我的行可以有不同的值)。Android - 自定義listView,每行不同顏色
感謝任何想法
由於充氣的custom_row.xml改變充氣方法的 返回視圖的背景後的getView方法 你做的自定義列表視圖。請參閱下面的示例片段:
public getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.custom_xml, null);
do some stuff...
//let say you have an arraylist of color
convertView.setBackgroundColor(arraylist.get(position));
//in case that your color is limited, just re-use your color again
and some logic how to re-use the colors.
}
如果這可以幫助您,請將此帖標記爲答案。
謝謝。
在適配器,可以手動設置當視圖是使用getView方法檢索的視圖的背景顏色。
// set the background to green
v.setBackgroundColor(Color.GREEN);
在這裏使用其他答案阻止選擇器正常工作,選擇器停止突出顯示行完全。通過按照接受的答案中所述手動設置顏色,選擇器停止在滾動時突出顯示行。因此,讓我描述一個不會讓選擇器混亂的解決方案。
This article正在描述如何用透明度來解決這個問題,但是我不能真正使它工作。所以對我來說,解決方案是我的可繪製文件夾中有兩個列表選擇器。這樣我可以在運行時設置兩種不同的背景顏色,並保持選擇器正常工作。
list_selector_darkgrey.xml我深灰色線
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/gradient_bg_darkgrey" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="false" android:state_selected="true"/>
</selector>
和list_selector.xml爲淺灰色線
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/gradient_bg" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="false" android:state_selected="true"/>
</selector>
請忽略繪製梯度,你可以用你的顏色替換它。
在BaseAdapter類中,我將調用setBackgroundResource將一些行顯示爲淺灰色,將其他行顯示爲深灰色。選擇器顏色與XML文件中的相同並定義。
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
... some logic ...
if (... some condition ...) {
vi.setBackgroundResource(R.drawable.list_selector_darkgrey);
}
else {
vi.setBackgroundResource(R.drawable.list_selector);
}
return vi;
}