1

I have variety of buttons and I would like to get their background color, getting background color in a color drawable is easy but it is not easy in ripple drawable, how can I manage to get background color from ripple drawable.

Mike
  • 301
  • 2
  • 7
  • 19

3 Answers3

3

Try this:

 RippleDrawable rippleDrawable = (RippleDrawable) button.getBackground();
 Drawable.ConstantState state = rippleDrawable.getConstantState();
 try {
     Field colorField = state.getClass().getDeclaredField("mColor");
     colorField.setAccessible(true);
     ColorStateList colorStateList = (ColorStateList) colorField.get(state);
     int rippleColor = colorStateList.getDefaultColor();
  } catch (NoSuchFieldException e) {
      e.printStackTrace();
  } catch (IllegalAccessException e) {
      e.printStackTrace();
  }
shhp
  • 3,653
  • 2
  • 18
  • 23
  • for default button background colour which looks to be something close to #ffd6d7d7, your code returns #1f000000. How can I pick the right state, ie the state before the button is clicked? thx – rockhammer Oct 22 '16 at 22:50
  • @rockhammer you can try `ColorStateList.getColorForState` – shhp Oct 24 '16 at 02:03
  • thx for suggestion... took me a while to figure out how to work `.getState()` & `.getColorForState()`. Inserting `int[] statesOther = rippleDrawable.getState();` before `try` and a for loop within `try` to do `coloursOther[i] = colorStateList.getColorForState(new int[]{statesOther[i]}, 0);`, the entire `coloursOther[]` array and `rippleColor` return #1f000000. Then I thought may be that's coz I have this code in the `onClick()` so it would only show states relating to being clicked. Even when I put this code in `onCreate()` or `onWindowFocusChanged()`, I'm only getting #1f000000 – rockhammer Oct 25 '16 at 14:26
  • 1
    I have the same issue, I'm getting the ripple effect's color, but what I want is the color of the AppCompatButton that has the RippleDrawable as its background. Maybe the color isn't stored in the RippleDrawable's ColorStateList, but where is it then..? If I set the background to null, then the button becomes transparent. So the color is somewhere in the RippleDrawable. – Cybrosys May 08 '17 at 08:16
  • `getDefaultColor` returns a big number like 352321535. How can I convert this number in a color? – capo11 Jun 04 '20 at 09:49
  • @capo11 `Color.parse("#"+Long.toHexString(352321535))` – shhp Jun 08 '20 at 09:14
1

The solution that I found was to remove entries from the manifest of a newly minted app - particularly look at styles, themes and colours - compare older working apps with the new one to determine suspects. The RippleDrawable then replaced itself with the ColorDrawable that it had been and .getColor() works again.

-2

please check following example for ripple effect in android..

http://www.viralandroid.com/2015/09/how-to-add-ripple-effect-to-android-button.html

malli
  • 642
  • 2
  • 12
  • 30