Friday, 7 March 2025

Snackbar in Kotlin

How to show snackbar in place of toast message , below is the code for showing snackbar in kotlin. Below code is put in Utils.kt  (common file) or you can write this code in current activity also , but when we need this function multiple time so we use common function and write this code in Utils.kt .


fun showSnackbar(view: View, message: String, activity: Activity ,actionText: String? = null, action: (() -> Unit)? = null) {
    val snackbar = Snackbar.make(view, "message", Snackbar.LENGTH_LONG)
        .setBackgroundTint(Color.WHITE) // Customize background color
        .setTextColor(Color.BLACK)    // Customize text color

    val snackbarView = snackbar.view

   
// Set width and position
    val params = snackbarView.layoutParams as FrameLayout.LayoutParams
    params.width = 1000 // Custom width
    params.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM // Center it

    // Set bottom margin (e.g., 100px)
    params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, 100)
    snackbarView.layoutParams = params

    // Change message text size
    val snackbarText = snackbarView.findViewById<TextView>(com.google.android.material.R.id.snackbar_text)
    snackbarText.textSize = 25f // Set text size in SP
    snackbarText.setTypeface(null, Typeface.NORMAL) // Optional: Make text bold


    // Change action button text size
    val snackbarAction = snackbarView.findViewById<TextView>(com.google.android.material.R.id.snackbar_action)
    snackbarAction.textSize = 25f // Set button text size (SP)
    snackbarAction.setTypeface(null, Typeface.NORMAL) // Optional: Make button text bold

    actionText?.let {
       
snackbar.setAction(it) { action?.invoke() }
       
snackbar.setActionTextColor(Color.BLACK) // Customize action button color
    }

   
snackbar.show()

    // Auto dismiss after 20 seconds and navigate to Home
    Handler(Looper.getMainLooper()).postDelayed({
       
if (snackbar.isShown) {
            snackbar.dismiss()
        }
       activity.finish()
    }, 4000) // 40 seconds delay
}          

  

Now , use this function in our activity.


showSnackbar(binding.root, message, this,"OK") {
   
//Toast.makeText(this, "OK clicked", Toast.LENGTH_SHORT).show()
    finish()
}


No comments:

Post a Comment

Comments

Snackbar in Kotlin

How to show snackbar in place of toast message , below is the code for showing snackbar in kotlin. Below code is put in Utils.kt  (common fi...