首先要自定义ListView item 的点击效果有三种方法
第一种,直接通过ListView的属性设置
<ListView android:id="@+id/listview" android:layout_width="match_parent" android:listSelector="@drawable/list_selector" android:layout_height="match_parent"></ListView>
第二种在item 的 View 的layout 的根布局下设置background
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/listt_selector" android:layout_height="50dp" android:descendantFocusability="blocksDescendants"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_centerVertical="true" android:layout_height="wrap_content" android:text="Medium Text" /> <ImageView android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> </RelativeLayout>
第三中方法是在adapter的getView()方法中设置,同时这种方法也是最灵活的,可以根据不同位置来设置不同的点击效果和背景
@Override public View getView(int position, View convertView, ViewGroup parent) { CommonItem commonItem = null; if (convertView == null) { commonItem = new CommonItem(MainActivity.this); } else { commonItem = (CommonItem) convertView; } commonItem.setText(languages[position]); if (position == 0) { commonItem.setBg(R.drawable.language_first_item_selector); } else if (position == languages.length - 1) { commonItem.setBg(R.drawable.language_last_item_selector); } else { commonItem.setBg(R.drawable.language_item_selector); } return commonItem; }以上三种方法都可一实现自定义listView item 的自定义的点击效果。
在第二和第三中方法中,设置好了背景之后,会遇到,Item不能相应ListView的onItemClick点击事件,
原因:
ListView中的Item内部的View获得了焦点,如Button, Checkbox等。
解决办法:
不要让ListView中的Item内部的View获得焦点就OK了,这样做:android:descendantFocusability="blocksDescendants"(放在item View 的根布局的属性)
public static final int descendantFocusability
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Constant | Value | Description |
beforeDescendants | 0 | The ViewGroup will get focus before any of its descendants. |
afterDescendants | 1 | The ViewGroup will get focus only if none of its descendants want it. |
blocksDescendants | 2 | The ViewGroup will block its descendants from receiving focus. |
注意:
还有一种情况也会导致OnItemClickListener或OnItemLongClickListener回调不会执行,那就是ListView的child设置了onClickListener或onLongClickListener。我们可以通过源代码看出,在你调用setOnClickListener()方法后,它会调用setClickable(true),在onTouchEvent里面的实现如下:
- if (((viewFlags & CLICKABLE) == CLICKABLE ||
- (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
- // ....
- return true;
- }
当一个View在onTouchEvent里面返回true后,ListView就不会正常接收到事件。