我有一个不同颜色的列表视图,具体取决于它是偶数行还是奇数行:
我的自定义适配器:
if ( position % 2 == 0)
convertView.setBackgroundResource(R.layout.listview_selector_even);
else
convertView.setBackgroundResource(R.layout.listview_selector_odd);
list_selector_even:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@layout/even_row" android:state_enabled="true"/>
<item android:drawable="@layout/even_row" android:state_pressed="true"/>
<item android:drawable="@layout/even_row" android:state_focused="true"/>
</selector>
list_selector_odd:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@layout/odd_row" android:state_enabled="true"/>
<item android:drawable="@layout/odd_row" android:state_pressed="true"/>
<item android:drawable="@layout/odd_row" android:state_focused="true"/>
</selector>
even_row:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />
</shape>
odd_row:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#F0F0F0"/>
<padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />
</shape>
我有点失落,因为我无法使用渐变效果处理偶数和奇数行颜色。对于预先设定的效果渐变,我有下一个代码:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="#3E5260"
android:endColor="#3E5260"
android:angle="270" />
</shape>
</item>
</selector>
感谢您的帮助!
答案 0 :(得分:2)
您已经检查了选择器中的状态,因此对于渐变,您应该这样做:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#3E5260"
android:endColor="#3E5260"
android:angle="270" />
</shape>
此外,要么将选择器更改为跟随并为每个选择器项定义文件,要么将具有所有可用状态的选择器移动到odd_row.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@layout/odd_row_pressed" android:state_pressed="true"/>
<item android:drawable="@layout/odd_row_focused" android:state_focused="true"/>
<item android:drawable="@layout/odd_row_enabled"/>
</selector>
此版本可确保在未按下项目且未聚焦的情况下选择odd_row_enabled.xml。如果您想要另一个布局,如果未启用该项,则必须再添加一行(在默认行之前)。此外,它确保在按下并启用时选择odd_row_pressed.xml,因为按下的状态的<item>
位于其他行之前。