Initially, I wanted to make Toast with a custom layout, but then I saw that starting from Android 11, it was not desirable to do this, and the setView() method for Toast became deprecated. I decided to try to do the same, but only for the Snackbar.
my xml code for my custom Snackbar:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/blue"
app:cardCornerRadius="20dp"
app:contentPaddingBottom="4dp"
app:contentPaddingLeft="12dp"
app:contentPaddingRight="12dp"
app:contentPaddingTop="4dp">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/text_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableEnd="@drawable/ic_vector_check_mark_white"
android:drawablePadding="4dp"
android:fontFamily="@font/tt_hoves_medium"
android:text="Copied"
android:textAlignment="center"
android:textColor="@color/white"
android:textSize="10sp" />
</androidx.cardview.widget.CardView>
Kotlin function for show SnackBar:
private fun showSnack() {
val snackbar = Snackbar.make(binding.root, "", Snackbar.LENGTH_SHORT)
snackbar.view.setBackgroundColor(Color.TRANSPARENT)
val customSnackView: View = layoutInflater.inflate(R.layout.component_toast_message, null)
val snackbarLayout = snackbar.view as Snackbar.SnackbarLayout
snackbarLayout.setPadding(0, 0, 0, 0)
snackbarLayout.addView(customSnackView)
snackbar.show()
}
However, I ran into a problem that my Snackbar has a match_parant width, although I need it to have the size of the View itself, that is, wrap_content, but using various methods I could not achieve this. Is there any solution for this?


You should probably try Toast. Much simpler and match your requirement.
If you still want to make your SnackBar not matching parent you could try adding layoutParams programatically like this:
val layoutParams = snackbarLayout.layoutParams as ViewGroup.MarginLayoutParamslayoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENTsnackbarLayout.layoutParams = layoutParamsI hope it work!