M D
M D

Reputation: 47807

Clickable LinearLayout not Highlight on click

In my Android app, I have a LinearLayout View that contains other views. The LinearLayout is clickable, but when it is clicked, it does not highlight orange like it should.I already tried with selector but it is not working.

How can I get it to highlight ?

Upvotes: 1

Views: 2085

Answers (2)

David Boyd
David Boyd

Reputation: 6601

If you had a lot of these LinearLayouts, let's say with different background colors, and you only wanted to use a single selector to handle the highlight for all of them, you could use the following approach:

res/resources/dimens.xml

<resources>
    <color name="button_focused">#60ffffff</color>
</resources>

res/drawable/button_selector.xml

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@color/button_focused" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@android:color/transparent" /> <!-- focused -->
     <item android:drawable="@android:color/transparent" /> <!-- default -->
 </selector>

Then in your layout, wrap your LinearLayout with a FrameLayout like so:

<FrameLayout
    android:layout_width="56dp"
    android:layout_height="56dp"
    android:foreground="@drawable/button_selector">

    <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:background="#F68D5D">
    </LinearLayout>                
</FrameLayout>    

A downside to this is that you add another layer to your layout tree.

Upvotes: 2

Carlo Solano
Carlo Solano

Reputation: 103

If you want the highlight to be orange, you can use this in your LinearLayout

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

It is Android's default list selector color. You can also customize the color by creating your own drawable. Something like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/item_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/item_focused" android:state_focused="true" />
    <item android:drawable="@drawable/item_checked" android:state_checked="true" />
    <item android:drawable="@drawable/item_activated" android:state_selected="true" />
    <item android:drawable="@drawable/item_activated" android:state_activated="true" />
    <item android:drawable="@android:color/transparent" />
</selector>

Upvotes: 4

Related Questions