Skip to content

Instantly share code, notes, and snippets.

@scottyab
Created October 23, 2018 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottyab/31ea005e10a9115b55ee6501fac866bf to your computer and use it in GitHub Desktop.
Save scottyab/31ea005e10a9115b55ee6501fac866bf to your computer and use it in GitHub Desktop.
snippet from me trying to get color states working for buttons based off https://gist.github.com/milosmns/6566ca9e3b756d922aa5
fun getPressedColorSelector(normalColor: Int, pressedColor: Int, disabledColor: Int): ColorStateList {
val states =
arrayOf(intArrayOf(android.R.attr.state_pressed), // pressed
intArrayOf(-android.R.attr.state_enabled), // disabled
intArrayOf(android.R.attr.state_focused), //focused
intArrayOf() //empty aka normal
)
val colors = intArrayOf(
pressedColor,
disabledColor,
pressedColor,
normalColor
)
return ColorStateList(states, colors)
}
/**
* Very similar to [.createContrastStateDrawable] but
* creates a Ripple drawable available in Lollipop.
*
* @param normal Color normal state of the drawable to this color
* @param clickedBackground Background color of the View that will show when view is clicked
* @param original This drawable will be contrasted to the `clickedBackground` color on press
* @return The Ripple drawable that is in contrast with the on-click background color
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun createContrastRippleDrawable(normal: Int, clickedBackground: Int, disabledColor: Int, original: Drawable?): Drawable {
if (original == null) {
return createRippleDrawable(normal, clickedBackground, null)
}
//return RippleDrawable(ColorStateList.valueOf(clickedBackground), original, ColorDrawable(clickedBackground))
return RippleDrawable(getPressedColorSelector(normal, clickedBackground, disabledColor), original, ColorDrawable(clickedBackground))
//.........................^
}
/**
* Creates a new `RippleDrawable` used in Lollipop and later.
*
* @param normalColor Color for the idle ripple state
* @param rippleColor Color for the clicked, pressed and focused ripple states
* @param bounds Clip/mask drawable to these rectangle bounds
* @return A fully colored RippleDrawable instance
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun createRippleDrawable(normalColor: Int, rippleColor: Int, bounds: Rect?): Drawable {
var maskDrawable: ColorDrawable? = null
if (bounds != null) {
maskDrawable = ColorDrawable(Color.WHITE)
maskDrawable.bounds = bounds!!
}
return if (normalColor == Color.TRANSPARENT) {
RippleDrawable(ColorStateList.valueOf(rippleColor), null, maskDrawable)
} else {
RippleDrawable(ColorStateList.valueOf(rippleColor), ColorDrawable(normalColor), maskDrawable)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment