热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Listview点击事件失效问题解决以及每个Item子控件获取focus

最近在写一个开源的播放器,碰到了一问题,就是listview在自定义item的内容之后点击出现无效,后来才发现原来是因为当item里面包含了子控件,例如TextView、Button等

最近在写一个开源的播放器,碰到了一问题,就是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


<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


<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>

推荐阅读
author-avatar
mobiledu2502915347
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有