Android Create Singleton Class for Toast Message

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Toast messages are the most simple way of providing feedback to the user. By default, Android provide gray color message toast where we can set the message and the duration of the message. If we need to create more customizable and reusable toast message, we can implement it by ourselves with the use of a custom layout. More importantly when we are implementing it, the use of Singelton design pattern will make it easy for maintaining and development of the custom toast message class.

Syntax

  • Toast Toast(Context contex)
  • void setDuration(int duration)
  • void setGravity(int gravity, int xOffset, int yOffset)
  • void setView(View view)
  • void show()

Parameters

Parameterdetails
contextRelevant context which needs to display your toast message. If you use this in the activity pass "this" keyword or If you use in fragement pass as "getActivity()".
viewCreate a custom view and pass that view object to this.
gravityPass the gravity position of the toaster. All the position has added under the Gravity class as the static variables . The Most common positions are Gravity.TOP, Gravity.BOTTOM, Gravity.LEFT, Gravity.RIGHT.
xOffsetHorizontal offset of the toast message.
yOffsetVertical offset of the toast message.
durationDuration of the toast show. We can set either Toast.LENGTH_SHORT or Toast.LENGTH_LONG

Remarks

Toast message is a simple way of providing feedback to user about something is happening. If you need a more advanced way to give feedback you can use dialogs or snackbar.

To get more details about the toast message please check this documentation. https://developer.android.com/reference/android/widget/Toast.html



Got any Android Question?