android code

[Android] ListView에서 클릭이 제대로 인식되지 않는 문제

paulaner80 2016. 5. 31. 16:43
반응형


1. 증상

ListView의 setOnItemClickListener에다가 AdapterView.OnItemClickListener을 정확히 넘겨주었음에도 불구하고
정작 Item을 클릭하였을 때 클릭 이벤트가 발생하지 않는 문제가 발생하였다.

2. 원인

ListView의 각 Item이 여러 View들을 조합한 Layout일 때, ListView에서 클릭을 하면 우리가 으레 생각하는 것 처럼 해당 List Item을 클릭하는 것이 아니라 표면에 나와있는 Item 안쪽 각각의 View를 클릭하는 것으로 인식한다.

3. 해결책

Item의 레이아웃 파일로 가서 루트 레이아웃에다가 android:descendantFocusability="blocksDescendants" 삽입. 이렇게 하면 Focus 단계를 자체적으로 낮추게 되어 Item 그 자체를 클릭하게끔 만든다.


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

                android:orientation="horizontal"

                android:layout_width="match_parent"

                android:layout_height="55dip"

                android:paddingStart="10dip"

                android:paddingEnd="10dip"

                android:layout_marginTop="5dip"

                android:background="#ffffff"

                android:descendantFocusability="blocksDescendants">

    <LinearLayout

        android:orientation="vertical"

        android:layout_width="0dip"

        android:layout_weight="1"

        android:layout_height="match_parent"

        android:gravity="center_vertical"

        >

        <TextView

            android:id="@+id/txtToDoName"

            android:text="ToDo Name"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:textSize="20sp"

            android:gravity="bottom"

            android:ellipsize="end"

            android:singleLine="true"/>

        <TextView

            android:id="@+id/txtDate"

            android:text="07.22"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:textSize="15sp"

            android:gravity="top"/>

    </LinearLayout>

    <CheckBox

        android:id="@+id/chk_finish"

        android:layout_width="wrap_content"

        android:layout_height="match_parent"/>

</LinearLayout>