Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to attach Snackbar's lifecycle to fragment?

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))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading