I have a LinearLayout
that I\'ve styled to look like a button
, and it contains a few text/ImageView elements. I would like to make the whole
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"
Just add background attr/selectableItemBackground to linear layout and also make that linearlayout clickable
example :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linear1"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">
That's make linearlayout act like button when it pressed. :)
Previous aswers was about how to set default background in xml file. Here same thing in code:
linearLayout1.setBackgroundResource(android.R.drawable.list_selector_background);
This was helpful but if you want to put a background color and make linear layout clickable like the list item. Set the background with your preferred color and set foreground color to ?android:attr/selectableItemBackground, set focusable true, and clickable true
sample code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#FF0"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:onClick="onClickMethod"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
/>
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.
Just Use This:
android:foreground="?attr/selectableItemBackground"