Issue
We are trying to create a Snackbar. The code from a Java app was converted using the Java to Kotlin converter in Android Studio. Next we looked at various examples on many different websites and even tried to implement the code from the book Kotlin Programming Cookbook. We will post all our non working examples below. Our question is how to create the proper syntax to show a Snackbar? We would like to click a btnSNACK with a onClick=onSNACK to show the Snackbar
This is our Java to Kotlin converter code we would really like to use this one
fun onSNACK(view: View){
//Snackbar(view)
//val snackbar = Snackbar(view, "Permission Granted", Snackbar.LENGTH_LONG).setAction("Action", null).show()
snackbar.make(view, "Replace with your own action",
snackbar.LENGTH_LONG).setAction("Action", null).show()
snackbar.setActionTextColor(Color.BLUE)
val snackbarView = snackbar.getView()
snackbarView.setBackgroundColor(Color.LTGRAY)
val textView =
snackbarView.findViewById(android.support.design.R.id.snackbar_text)
textView.setTextColor(Color.BLUE)
textView.setTextSize(28f)
snackbar.show()
}
Next Try was with this code
class Snackbar{
object LENGTH_LONG {
}
fun show() {
}
}
fun onSNACK(view: View){
snackbar = Snackbar.make(this, "Welcome to Android Teachers..!!",
Snackbar.LENGTH_LONG)
snackbar.show()
}
Our layout is a RelativeLayout (RL) for the Activity that has the Snackbar
class Snackbar(view: View?): Any() {
object LENGTH_SHORT {}
fun View.snack(message: String, length: Int = Toast.LENGTH_LONG, f: Snackbar.
() -> Unit) {
val snack = Snackbar.make(this.findViewById(R.id.RL), message, length)
snack.f()
snack.show()
}
We thought this would work the first line of code was declared top level
lateinit var snackbar: Snackbar//top level
fun onSNACK(){
btnSNACK.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
We used the class Snackbar with and without these various methods. We were able to remove all the red warnings in most of these examples but the work "make" just offers the same suggestion "change variable name" which makes no sense from our Kotlin novice point of view. We do not desire to use Anko plugin We also see no imports that refer to Snackbar Yes we have jetbrains stdlib v7 dependency no design dependency
Solution
and then here's your modified code which will show snack bar
fun onSNACK(view: View){
//Snackbar(view)
val snackbar = Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG).setAction("Action", null)
snackbar.setActionTextColor(Color.BLUE)
val snackbarView = snackbar.view
snackbarView.setBackgroundColor(Color.LTGRAY)
val textView =
snackbarView.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
textView.setTextColor(Color.BLUE)
textView.textSize = 28f
snackbar.show()
}
Answered By - SSB
Answer Checked By - David Goodson (JavaFixing Volunteer)