如何以编程方式设置listview的选择颜色

时间:2016-05-21 11:28:46

标签: android

xml的{​​{1}}文件中,我使用ListView为选择列表项上的设置颜色,这很正常。但我想以编程方式设置此颜色。那么请告诉我该怎么做?

3 个答案:

答案 0 :(得分:3)

yourListView.setSelector(R.color.colorname);

<强> colors.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
         <color name="colorname">#333333</color>
//other colors
    </resources>

答案 1 :(得分:0)

我会尝试

listVIew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        view.setBackgroundColor(ContextCompat.getColor(context,R.id.color));
    }
});

答案 2 :(得分:0)

item.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" 
    android:drawable="@drawable/pressed" />
<item  android:state_focused="false" 
    android:drawable="@drawable/normal" />
</selector>
ListView中的

 android:listSelector="@drawable/item"