Home > Blockchain >  How to attach Snackbar's lifecycle to fragment?
How to attach Snackbar's lifecycle to fragment?

Time:12-30

I'm using Snackbar in my app which has indefinite length. But when user leave this fragment i want my snackbar to gone. How can i do that? It's my first time working with snackbar. I used constraintLayout view from my fragment for it so i decided it's attached to fragment but why it's still exist after i leave fragment?

           Snackbar
            .make(binding.constraintLayout, getString(titleId), Snackbar.LENGTH_INDEFINITE)
            .setTextColor(Color.WHITE)
            .setActionTextColor(Color.WHITE)
            .setBackgroundTint(ContextCompat.getColor(requireActivity(), R.color.teal))

CodePudding user response:

Make a variable to store the Snackbar object returned by Snackbar.make(). Then call dismiss() in onDetach()

class YourFragment : Fragment(){

    var snackbar : Snackbar? = null
    
    fun createSnackbar()
    {
        snackbar = Snackbar
            .make(binding.constraintLayout, getString(titleId), Snackbar.LENGTH_INDEFINITE)
            .setTextColor(Color.WHITE)
            .setActionTextColor(Color.WHITE)
            .setBackgroundTint(ContextCompat.getColor(requireActivity(), R.color.teal))
        snackbar?.show()
    }

    override fun onDetach()
    {
        snackbar?.takeIf{it.isShown}?.dismiss()
    }

}
  • Related