Create a snackbar
Kotlin code to create and configure a snackbar:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// Run this action if user clicks on snackbar Action Text class CustomSnackBarAction : View.OnClickListener { override fun onClick(v: View) { oToast("This device is not supported.") } } // Declare snackbar variables val currentView: View = this.findViewById(android.R.id.content) val snackBar = Snackbar.make( currentView, "This text will appear on the snackbar.", Snackbar.LENGTH_INDEFINITE ) // Specify how Action Text should look and behave snackBar.setAction("OK", CustomSnackBarAction()) snackBar.setActionTextColor(Color.WHITE) snackBar.setTextColor(Color.YELLOW) snackBar.setMaxInlineActionWidth(500) // Configure background of the snackbar val snackBarView = snackBar.view snackBarView.setBackgroundColor(Color.DKGRAY) // Configure text on the snackbar val textView = snackBarView.findViewById(com.google.android.material.R.id.snackbar_text) as TextView textView.setTextColor(Color.YELLOW) textView.textSize = 28f textView.maxLines = 5 // Show the snackbar snackBar.show()
Where:
- 2️⃣ - Declare a function that runs whenever the user clicks the Action Text on the snackbar
- 4️⃣ - This is a custom function to generate a Toast message.
- 9️⃣ - Find current view and assign it to a variable
- 🔟 - Create a snackbar, but don't show it yet
- 1️⃣3️⃣ - Specify Snackbar.LENGTH_INDEFINITE so snackbar does not go away until user clicks the Action Text
- 1️⃣7️⃣ - Set the custom action that occurs if users click the Action Text
- 2️⃣4️⃣ - Set a custom bgcolor for the snackbar
- 2️⃣7️⃣ - Find snackbar text so we can modify its style
- 3️⃣1️⃣ - Number of maximum lines that the snackbar supports. If not set, Android Studio uses the default value of 1and will only show the text on one line.
- 3️⃣4️⃣ - Show the snackbar to the world
→