Home > Back-end >  Action in SnackBar called instantly when show
Action in SnackBar called instantly when show

Time:07-04

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
}

CodePudding user response:

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
}
  • Related