We could use custom Toast to display a message on screen. But with Android API 30 custom toasts and getView() method are deprecated.
The official document says;
Custom toast views are deprecated. Apps can create a standard text toast with the
makeText(android.content.Context, java.lang.CharSequence, int)method, or use a Snackbar when in the foreground. Starting from Android
Build.VERSION_CODES#R, apps targeting API level
Build.VERSION_CODES#Ror higher that are in the background will not have custom toast views displayed.
So according to the document we can use custom SnackBar instead of custom toast for the same purposes. Snackbars include user-actionable options, which can provide a better app experience.
Okay let’s create a layout file that will represent a custom snack bar;
Now we can create a file named Context.kt for extensions and write an extension function for Context;
This function takes 2 parameter. Our message and a View to hold Snackbar’s view from the value given to container. Then, we add layout that we created and bind it with DataBinding(dataBinding part is optional). After that, we can create a snackbar and add view(our parameter named container) and duration(just like toast message) to it. At last of course call show() function of snackbar.
Finally we can call this function from a Fragment like that;
requireContext().showCustomSnackBar(getString(R.string.saved), activity?.findViewById(android.R.id.content) )
We gave a message and root view for function parameters and now it’s ready to display a custom toast .