Android中ListView对Item设置点击事件无效的情况

在我做一个练手的项目的时候,定义了这样一个ListView的Item:

<?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="48dp"
    android:orientation="horizontal"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/tv_mine"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="6"
        android:text="个人资料"
        android:textSize="16sp"
        android:gravity="center_vertical"
        android:layout_marginLeft="10dp"/>

    <ImageButton
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:src="@drawable/ic_to"
        android:background="#FFF"/>
</LinearLayout>

在Java代码中设置了点击事件发现无法点击。

事实上,对于一个布局和控件来说,优先反馈子项的点击事件,当布局里有例如Button、ImageButton、CheckBox等控件是,会优先反馈这些控件的点击事件,这时我们需要在XML文件中设置:

android:descendantFocusability="blocksDescendants"

属性android:descendantFocusability的值有三种:

beforeDescendants:viewgroup会优先其子类控件而获取到焦点
afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点,也就是各有各的焦点

这样设置完就可以点击啦。

发布了40 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42650988/article/details/89218329