使线性布局可以像列表视图中的列表项一样选择(Android)

Mob*_*852 23 user-interface android listview android-linearlayout

我知道如何将一个onClick侦听器添加到LinearLayout以使整个布局成为一个单击目标,但是我想让LinearLayout在列表视图中像列表项一样被点击时突出显示.最好的方法是什么?

Bla*_*ght 28

我更喜欢更简单的方法:

<LinearLayout android:orientation="vertical"
              android:id="@+id/layoutIdentifier"
              android:clickable="true"
              android:background="?android:attr/selectableItemBackground"

              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <!-- put views here -->
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

你不能用这种方式改变状态按下的背景,但有时候你并不需要.


Jer*_*ady 14

我碰到了这个,这就是我提出来的.在布局中,将背景设置为可绘制资源:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/clickable_layout"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:background="@drawable/clickable"> 
...
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

然后在drawable中添加clickable.xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
    android:drawable="@android:drawable/list_selector_background" />      
</selector>
Run Code Online (Sandbox Code Playgroud)

然后,您是否要在活动中添加点击处理程序取决于您.