Search code examples
androidkotlinandroid-snackbar

Action in SnackBar called instantly when show


I'm trying to show my SnackBar but my action is being called instantly when shown and not when the button is clicked. Why is this happening?

fun showSnackBar(msg:String,btnMsg:String,action:Unit){
   SnackBar.make(binding.root,msg,Snackbar.LENGTH_SHORT)
   .setAction(btnMsg){
      action
   }
}.show()

And thats what I do when calling this method:

showSnackBar("Added","Undo",undoAction())

fun undoAction(){
  //here I delete an item from a list
}

Solution

  • Your method is trigger right away because you are executing your method and giving the result to the method showSnackBar.

    You must change your parameter from Unit to a Callback.

    fun showSnackBar(..., onActionClicked: () -> Unit){
       snackbar.setAction(btnMsg) { onActionClicked() }
    }
    
    showSnackBar("Added", "Undo"){ 
      // here I delete an item from a list
    }
    

    or

    showSnackBar("Added", "Undo") { undoAction() }
    
    fun undoAction(){
      // here I delete an item from a list
    }
    

    or

    showSnackBar("Added", "Undo", ::undoAction)
    
    fun undoAction() {
      // here I delete an item from a list
    }