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

MobileDev852 picture MobileDev852 · Apr 28, 2011 · Viewed 15.1k times · Source

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 list item in a list view. What's the best way to do this?

Answer

Blacklight picture Blacklight · Sep 5, 2014

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.