How can I be notified when a Snackbar has dismissed itself?

前端 未结 12 1555
陌清茗
陌清茗 2020-12-01 00:24

I\'m using a Snackbar from the com.android.support:design:22.2.0 library. I\'m using it to undo deletions. To make my life easier, I\'m going to make the UI loo

12条回答
  •  鱼传尺愫
    2020-12-01 01:22

    Thanks to @SergeyMilakov in Kotlin it is:

    @SuppressLint("WrongConstant") // Suppress an error when set duration.
    private fun showSnackbar() {
        val DURATION = 5000
    
        Snackbar.make(view!!, "Remove item?"), DURATION).apply {
            setAction("Undo") {
                // Your action when a button is clicked.
            }
            addCallback(object : BaseTransientBottomBar.BaseCallback() {
                /* override fun onShown(transientBottomBar: Snackbar?) {
                    super.onShown(transientBottomBar)
                    Timber.d("*** onShown")
                }*/
    
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    super.onDismissed(transientBottomBar, event)
                    if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {
                        // Your action when the Snackbar is closed and the button was not clicked.
                    }
    
                }
            })
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.black))
            setActionTextColor(ContextCompat.getColor(context, R.color.yellow))
            show()
        }
    }
    

    Note that Snackbar shows, even if you move to other screens (for instance, back). So, don't forget to check whether you make actions on the right screen.

    Also Snackbar doesn't restore after screen rotation.

提交回复
热议问题