如何更改所选项目的背景颜色?

时间:2017-01-30 09:22:18

标签: android android-layout listview

我正在使用此代码,但它什么也没做:

添加到我的列表视图中:

android:listSelector="@drawable/list_selector"

然后在drawable中使用xml文件来控制不同的状态

@绘制/ list_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>

@绘制/ list_item_bg_normal

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="#ff0000"
  android:endColor="#ffffff"
  android:angle="90" />
</shape>

@绘制/ list_item_bg_pressed

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#ff0000"
      android:endColor="#ffffff"
      android:angle="90" />
</shape>

在活动中:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        view.setSelected(true);

2 个答案:

答案 0 :(得分:0)

添加

adapter.notifydatasetchanged();


您的代码看起来像这样

  lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            view.setSelected(true);
            adapter.notifydatasetchanged();

答案 1 :(得分:0)

请更新您的选择器文件,如下所示,并调用通知数据集已更改。在适配器内部,您需要维护一个标志,以便在滚动列表时保持选择。

    <selector xmlns:android="http://schemas.android.com/apk/res/android">

      <item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
      <item android:drawable="@drawable/list_item_bg_pressed" android:state_selected="true"/>
      <item android:drawable="@drawable/list_item_bg_normal"/>
    </selector>

然后

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                list.get(position).isSelected=true; // list is array items passed to adapter
                adapter.notifydatasetchanged();
            )
    }

在适配器的getView方法中 通过使用类似

的布尔值来维护选择
@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
     if(list.get(position).isSelected){
       convertview.setSelected(true)
     }else{
       convertview.setSelected(false)
     }
}