Skip to content

Instantly share code, notes, and snippets.

@alwarren
Forked from antoniolg/HomeActivity.kt
Last active March 8, 2018 05:22
Show Gist options
  • Save alwarren/2bc27c93b910eb0b45f2d78223248e7a to your computer and use it in GitHub Desktop.
Save alwarren/2bc27c93b910eb0b45f2d78223248e7a to your computer and use it in GitHub Desktop.
Snackbar extensions on Kotlin, to create a useful small DSL.
fun Context.colorInt(color: Int) = ContextCompat.getColor(this, color)
inline fun View.snack(@IntegerRes messageRes: Int, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
snack(resources.getString(messageRes), length, f)
}
inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
snack.f()
snack.show()
}
inline fun View.snack(message: String, bgColor: Int? = null, length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
bgColor?.let{snack.view.setBackgroundColor(bgColor)}
snack.f()
snack.show()
}
fun Snackbar.action(@IntegerRes actionRes: Int, color: Int? = null, listener: (View) -> Unit) {
action(view.resources.getString(actionRes), color, listener)
}
fun Snackbar.action(action: String, color: Int? = null, listener: (View) -> Unit) {
setAction(action, listener)
color?.let { setActionTextColor(color) }
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
setSupportActionBar(toolbar)
fab.setOnClickListener {
it.snack("Snack message", bgColor = colorInt(R.color.red)) {
action("Action", colorInt(R.color.white)) { toast("Action clicked") }
}
}
}
}
@alwarren
Copy link
Author

alwarren commented Mar 8, 2018

Added a context extension to covert a resource color to a ColorInt.

Added a view extension to accept a background color for the snack bar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment