Skip to content

Instantly share code, notes, and snippets.

@RicardAparicio
Created July 10, 2019 14:28
Show Gist options
  • Save RicardAparicio/7cadd20da76f3e6f915bd44a1ded2e00 to your computer and use it in GitHub Desktop.
Save RicardAparicio/7cadd20da76f3e6f915bd44a1ded2e00 to your computer and use it in GitHub Desktop.
Approach to show Android Snackbars
import android.graphics.Color
import android.view.View
import androidx.annotation.ColorInt
import androidx.databinding.BindingAdapter
import androidx.databinding.ObservableField
import com.google.android.material.snackbar.Snackbar
/**
* Created by Ricard Aparicio on 04/04/2019.
* ricard.aparicio@inqbarna.com
*/
interface IBindingSnackProvider {
val snackMessage: ObservableField<ConsumableSnackMessage>
fun showSnack(snackMessage: SnackMessage)
}
class BindingSnackProvider : IBindingSnackProvider {
override val snackMessage: ObservableField<ConsumableSnackMessage> by lazy { ObservableField<ConsumableSnackMessage>() }
override fun showSnack(snackMessage: SnackMessage) {
this.snackMessage.set(ConsumableSnackMessage(snackMessage.message, snackMessage.actionData))
}
}
open class SnackMessage(val message: String, val actionData: SnackActionData? = null)
data class ConsumableSnackMessage(val msg: String, val actData: SnackActionData? = null) :
SnackMessage(msg, actData) {
var consumed = false
}
data class SnackActionData(
val message: String,
@ColorInt val color: Int = Color.CYAN,
val clickListener: () -> Unit
)
@BindingAdapter("snackMessage")
fun View.showSnackbar(snackMessage: SnackMessage?) {
snackMessage?.let {
val showSnackFun: () -> Unit = {
Snackbar.make(this, snackMessage.message, Snackbar.LENGTH_LONG).apply {
snackMessage.actionData?.let { data ->
setAction(data.message) { data.clickListener() }
setActionTextColor(data.color)
}
}.show()
}
if (snackMessage is ConsumableSnackMessage) {
if (snackMessage.consumed.not()) {
showSnackFun()
}
snackMessage.consumed = true
} else {
showSnackFun()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment