为ListView同时设置点击时的背景和点击松手之后的背景

本例要达到的效果是,

(1)点击ListView的item时会有指定的背景,

(2)松手之后,刚才点击的item也会有指定的背景


实现(1)很简单:在xml中为ListView设置listSelector即可。

<ListView
        android:id="@+id/pop_listview_left"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none"
        android:divider="@color/popup_left_bg"
        android:dividerHeight="1dp"
        android:listSelector="@color/popup_right_bg"
        android:scrollingCache="false"
        />

实现(2)也很简单,在adapter中动态改变背景:

if (position == selectedPosition){
            convertView.setBackgroundResource(R.color.left_selected);
        }else{
            convertView.setBackgroundResource(R.color.left_normal);
        }
并且在该ListView的点击事件中及时更新selectedPosition:

leftLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //更新背景色
                FirstClassAdapter adapter = (FirstClassAdapter) (parent.getAdapter());
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetChanged();
            }
        });

可是,问题出来了:设置了(2)之后,(1)的效果没了!!!

这是因为,在设置

convertView.setBackgroundResource(R.color.left_selected);

时,(1)中listSelector中指定的颜色会被覆盖。

解决方法有两种:

(一)

将convertView的一个纯色的背景改为一个selector,并设置其在点击时的颜色为透明(这样下面listSelector的颜色就露出来了)。以下是selector_left_normal.xml和selector_left_selected.xml.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@android:color/transparent"/>

    <item android:state_pressed="false"
        android:drawable="@color/popup_left_bg"/>
</selector>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@android:color/transparent"/>

    <item android:state_pressed="false"
        android:drawable="@color/popup_right_bg"/>
</selector>

然后将(2)中的代码改为:

if (position == selectedPosition){
            convertView.setBackgroundResource(R.drawable.selector_left_selected);
        }else{
            convertView.setBackgroundResource(R.drawable.selector_left_normal);
        }

(二)

参照(一),将ListView的listSelector属性去掉,并将其颜色复制到上面两个selector中替换transparent那个颜色。

也就是说,每次点击ListView的条目之后,设置背景色时,

(a)如果该条目现在是选中状态,则直接设为某一个颜色

(b)否则,将其颜色设置为一个selector,并在selector中分别指定点击和没有点击时的颜色。

问题圆满解决。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值