Transparent background in ImageButton with ripple effect?
Asked Answered
B

3

28

I want to programmatically remove the grey background in ImageButton. I tried many method of removing it like -

imageButton.setBackgroundDrawable(null);

but on implementing them, I don't get the ripple effect on the ImageButton on touch. (No highlighting on touch).

Is there any way to remove the background but preserve the ripple effect or highlight.

Bicameral answered 21/5, 2015 at 4:21 Comment(1)
Possible duplicate of How to set background highlight to a LinearLayout?Essary
A
49

If android:background="?attr/selectableItemBackground" this works than I believe this answer should solve your problem:

https://mcmap.net/q/27164/-how-to-set-ripple-effect-on-a-linearlayout-programmatically

Amphitrite answered 21/5, 2015 at 4:30 Comment(2)
Or even better, android:background="?attr/selectableItemBackgroundBorderless"Entice
This will crash on some devices.Towage
A
13

Create your own RippleDrawable and you need to use mask for the Ripple if you're going to use transparent background.

 <!-- A red ripple masked against an opaque rectangle. -->
 <ripple android:color="#ffff0000">
   <item android:id="@android:id/mask"
         android:drawable="@android:color/white" />
 </ripple>
Angieangil answered 25/5, 2015 at 7:16 Comment(1)
<ripple> requires API level 21 (current min is 17) all the good stuff is obviously going to be useful in a few years when users have upgraded...Erinn
S
0

To have a transparent background with ripple effect, the background Drawable needs to be a rippleDrawable, which can be transparent. Set it up programmatically like this.

var mask = new android.graphics.drawable.GradientDrawable();
mask.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
mask.setColor(0xFF000000); // the color is irrelevant here, only the alpha
mask.setCornerRadius(5); // you can have a rounded corner for the effect

var rippleColorLst = android.content.res.ColorStateList.valueOf(
    android.graphics.Color.argb(255,50,150,255) // set the color of the ripple effect
);

// aaaand
var ripple = new android.graphics.drawable.RippleDrawable(rippleColorLst,null,mask);
yourImageButton.setBackground(ripple);

(Sorry for the JavaScript/NativeScript code, hope everyone can understand it)

Sealey answered 25/6, 2018 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.