【问题标题】:Make linear layout selectable like a list item in a list view (Android)使线性布局像列表视图中的列表项一样可选择(Android)
【发布时间】:2011-04-28 15:25:20
【问题描述】:

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

【问题讨论】:

    标签: android listview user-interface android-linearlayout


    【解决方案1】:

    我更喜欢更简单的方式:

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

    您无法以这种方式更改状态按下的背景,但有时您并不需要这样做。

    【讨论】:

      【解决方案2】:

      我遇到了这个,这就是我想出的。在您的布局中,将背景设置为可绘制资源:

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

      然后在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>
      

      然后由你决定是否要在你的活动中添加点击处理程序。

      【讨论】:

        【解决方案3】:

        您可以设置布局内的所有元素clickable=false。然后,您应该通过将布局背景设置为某种颜色来模仿选择行为,并在单击布局时将所有其他背景设置为透明。您可以使用布局 id 作为索引来了解选择了哪个布局。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-14
          • 1970-01-01
          相关资源
          最近更新 更多