1.先導入函示庫(build.gradle: Module)
dependencies {
implementation 'com.google.android.material:material:1.3.0-alpha01'
}
2.程式碼範例
SnackBar用法
一般用法
Snackbar.make(view, "消息:測試", Snackbar.LENGTH_SHORT).show()

文字顏色和背景顏色
val snackBar = Snackbar.make(view, "消息:測試", Snackbar.LENGTH_SHORT)
val snackBarView = snackBar.view
snackBarView.run {
setBackgroundColor(Color.RED)
findViewById<TextView>(R.id.snackbar_text).setTextColor(Color.YELLOW)
}
snackBar.show()

設置點擊事件
Snackbar.make(view, "消息:測試", Snackbar.LENGTH_SHORT)
.setAction("確定") {
Toast.makeText(this, "打開訊息", Toast.LENGTH_SHORT).show()
}.show()

設置點擊文字顏色
Snackbar.make(view, "消息:測試", Snackbar.LENGTH_SHORT)
.setActionTextColor(Color.YELLOW)
.setAction("確定") {
Toast.makeText(this, "打開訊息", Toast.LENGTH_SHORT).show()
}.show()

设置SnackBar監聽
Snackbar.make(view, "消息:測試", Snackbar.LENGTH_SHORT)
.setActionTextColor(Color.YELLOW)
.setAction("確定") {
Toast.makeText(this, "打開訊息", Toast.LENGTH_SHORT).show()
}
.addCallback(object : Snackbar.Callback() {
override fun onShown(sb: Snackbar?) {
super.onShown(sb)
Toast.makeText(this@MainActivity, "onShown",Toast.LENGTH_SHORT).show()
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
Toast.makeText(this@MainActivity, "onDismissed", Toast.LENGTH_SHORT).show()
}
})
.show()