Make linear layout selectable like a list item in a list view (Android)

后端 未结 3 1081
太阳男子
太阳男子 2021-02-02 11:01

I know how to add an onClick listener to a LinearLayout to make the whole layout a click target, but I\'d like to have the LinearLayout get highlighted when tapped just like a l

相关标签:
3条回答
  • 2021-02-02 11:18

    I prefer a simpler way:

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

    You can't change the state-pressed background this way, but sometimes you don't really need to.

    0 讨论(0)
  • 2021-02-02 11:26

    You can set all the elements inside the layout clickable=false. Then you should mimic selection behavior by setting layout background to some color and set all the other ones with background transparent when a layout is clicked. You can use layout id as index to know which layout is selected.

    0 讨论(0)
  • 2021-02-02 11:41

    I ran into this and this is what I came up with. In your layout, set the background to a drawable resource:

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

    Then in drawable, add clickable.xml as so:

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

    Then it's up to you whether or not you want to add a click handler in your activity.

    0 讨论(0)
提交回复
热议问题