Home > OS >  Is there any alternative for Toast.setGravity() to support in android 11 and above devices?
Is there any alternative for Toast.setGravity() to support in android 11 and above devices?

Time:10-29

Is there any way that I can position my Toast message in the center of the screen? Since Toast.setGravity() is not supported for Android 11 and above devices(API level 30 and above) as per android official documentation. I am not able to position my toast in the center of the screen. I searched all over for the solution but had no luck. My requirement is, I want to display a message similar to toast to be displayed at the center of the screen. I used a snack bar, but that is not what I am expecting. It is not necessary for me to display toast. I just want something to mimic the same functionality as that of a toast i.e. display a feedback message at the center of the screen. Thank you.

CodePudding user response:

The restriction on setting gravity for Toasts applies only to text toasts (created using the Toast.makeText(...) method). You can create a regular toast (by calling standard constructor - Toast(activity)), set gravity and customize it by setting a custom view.

As a result, you get something like this:

val customToast = Toast(this).also {
  // View and duration has to be set 
  val view = LayoutInflater.from(context).inflate(R.layout.foo_custom_toast, null)
  it.setView(view)
  it.duration = Toast.LENGTH_LONG
  
  it.setGravity(Gravity.CENTER, 0, 0)
}

Also, you can check this question and this article, I think this will help you.

P.s If you only need to show the text in your toast then in the Toast's custom view add a textView and then, when setting up the toast (setting the custom view) set the text to this textView. Also, through customView, you can customize Toast as you like.

CodePudding user response:

Here's how to do it with a Snackbar, provided you have a screen-sized ConstraintLayout in your hierarchy.

In your main Activity's ConstraintLayout, add a horizontal guideline at the center of the screen:

    <androidx.constraintlayout.widget.Guideline
        android:id="@ id/centerHorizontalGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent=".50" />

Then in your Activity, you can set the anchor view of the Snackbar to this Guideline. Setting an anchor view tells it where to appear on the screen, instead of the default of the bottom.

fun showCenteredSnackbar(@StringRes messageId: Int, duration: Int = Snackbar.LENGTH_SHORT) {
    Snackbar.make(this, binding.container, getText(messageId), duration)
        .setAnchorView(binding.centerHorizontalGuideline)
        .show()
}

where binding.container is the ConstraintLayout.

Your fragments can call this function using (requireActivity() as MainActivity).showCenteredSnackbar().

  • Related