Making a LinearLayout act like an Button

I ran into this problem just now. You'll have to set the LinearLayout to clickable. You can either do this in the XML with

android:clickable="true"

Or in code with

yourLinearLayout.setClickable(true);

Cheers!


If you want add the Android default background behavior to make a Layout acts like a "clikable" View, set on the targeted Layout:

API 11+ (Pure Android):

android:background="?android:attr/selectableItemBackground"

API 7+ (Android + AppCompat Support Library):

android:background="?attr/selectableItemBackground"

Any API:

android:background="@android:drawable/list_selector_background"

Answers above still true but didn't help me for just add the default pressed and released UI state (like in a ListView for instance).


First you'll want a selector to define the different states. For example, in an XML file:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_normal" />
</selector>

I haven't tried it, but you can possibly set the LinearLayout's android:background to this selector, and set android:clickable to true and it'll work.

If it doesn't, you could switch to using a RelativeLayout, and make the first element a button with this selector as the background and fill_parent for its layout width and height. In this case, just use a regular Button and set android:background to your selector. You don't have to put text on your button.


I used the first and second answer. But my linearlayout has images and text with background color, so i had to change "background" to "foreground"

linearlayout

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"