Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android widget ripple background when clicked

How can I get a button on a WIDGET on Android to display the Material ripple when clicked?

<LinearLayout
    android:id="@+id/button_power"
    style="@style/MyStyle">
    <ImageView
        android:id="@+id/image_view_power"
        android:layout_width="@dimen/widget_button_image_size"
        android:layout_height="@dimen/widget_button_image_size"
        android:layout_gravity="center_horizontal"
        android:contentDescription="power"
        android:src="@drawable/baseline_power_settings_new_24"
        android:tint="@color/primary_text" />

    <TextView
        android:id="@+id/text_view_power"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="On"
        android:textColor="@color/primary_text"
        android:textSize="@dimen/widget_button_text_size" />
</LinearLayout>

style.xml

<style name="MyStyle" parent="Base.Widget.AppCompat.Button.Borderless">
    <item name="android:layout_width">@dimen/button_height</item>
    <item name="android:layout_height">@dimen/button_height</item>
    <item name="android:minHeight">0dp</item>
    <item name="android:padding">8dp</item>
    <item name="android:minWidth">0dp</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:drawablePadding">0dp</item>
    <item name="android:background">@color/white_pressed</item>
    <item name="android:clickable">true</item>
    <item name="android:focusable">true</item>
    <item name="android:orientation">vertical</item>
</style>

Above shows how I'm using a linear layout to represent a clickable button for the widget. It also includes the style details.

I tried adding the line

android:background="?attr/selectableItemBackground"

to the LinearLayout but got an error on the widget which stated "Problem loading widget". The problem also occurred if I moved the attribute to the style itself.

It looks like what I want to achieve is possible since the Google Drive widget on Android has this effect. How is this done?

Thank you!

like image 801
waylonion Avatar asked Feb 20 '26 19:02

waylonion


2 Answers

Add these attribute to your LinearLayout

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

Note: This will not work below lollipop.

like image 55
Gaurav Kumar Avatar answered Feb 23 '26 07:02

Gaurav Kumar


I was using

android:background="?selectableItemBackground"

issue was solved after using,

android:background="?android:attr/selectableItemBackground"
like image 21
Omkar T Avatar answered Feb 23 '26 07:02

Omkar T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!