最近在写一个开源的播放器,碰到了一问题,就是listview在自定义item的内容之后点击出现无效,后来才发现原来是因为当item里面包含了子控件,例如TextView、Button等之后,子控件会优先获得Focus焦点导致了父控件获取不到,所以我们必须要对其进行设置。
1、解决listview设置的OnItemClickListener()无效。
我们会发现在ListView中有一个属性descendantFocusability
值 | 注释 |
---|---|
beforeDescendants | viewgroup会优先其子类控件而获取到焦点 |
afterDescendants | viewgroup只有当其子类控件不需要获取焦点时才获取焦点 |
descendantFocusability | viewgroup会覆盖子类控件而直接获得焦点 |
所以我们如国只需要父控件有点击效果,直接进行设置
android:descendantFocusability="descendantFocusability"
即可。
2.设置父控件和子控件都有效果
对于有些情况我们需要子控件和父控件都有效果,则,我们可以设置Listview的:descendantFocusability为”descendantFocusability”,另外将子控件的所有的点击效果的控件的focusable全部设置成false,,代码例子如下
Item_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tx_songname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginTop="10sp"
android:text="流着泪说分手"
android:focusable="false"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10sp">
<TextView
android:id="@+id/tx_songauthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="金志文"
android:focusable="false"
/>
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/btn_gengduoinfo"
android:layout_width="30sp"
android:layout_height="30sp"
android:background="@drawable/gengduo"
android:layout_marginTop="5sp"
android:layout_alignParentRight="true"
android:layout_marginRight="15sp"
android:focusable="false"
/>
</RelativeLayout>
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
android:background="@drawable/wenwen">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80sp"
android:background="#cd5b45">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="音乐库"
android:layout_marginTop="40sp"
android:layout_centerHorizontal="true"
android:textSize="24sp"
android:id="@+id/textView2" />
</RelativeLayout>
<ListView
android:id="@+id/lv_songlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
>
</ListView>
</LinearLayout>