Jetpack Compose 中的自定义 Toast

Custom Toast in Jetpack Compose

我想要 Jetpack Compose 中的自定义 Toast,但没有找到任何与此相关的有用文档,我们将不胜感激

在版本 30(R) 之前,可以使用 setView 方法。如此处所述,现在要么使用标准 Toast,要么转到 Snackbar

Toast -> setView

/**
 * Set the view to show.
 *
 * @see #getView
 * @deprecated Custom toast views are deprecated. Apps can create a standard text toast with the
 *      {@link #makeText(Context, CharSequence, int)} method, or use a
 *      <a href="{@docRoot}reference/com/google/android/material/snackbar/Snackbar">Snackbar</a>
 *      when in the foreground. Starting from Android {@link Build.VERSION_CODES#R}, apps
 *      targeting API level {@link Build.VERSION_CODES#R} or higher that are in the background
 *      will not have custom toast views displayed.
 */
@Deprecated
public void setView(View view) {
    mNextView = view;
}

自定义 Toast 已弃用,取而代之的是 SnackBar。
所以他们大多不会在 Jetpack Compose 中获得支持。

参考。
.
Android code change deprecating Custom Toast with explaination

Deprecating custom toasts as discussed, the reasons are:

  • We're blocking background custom toasts for security reasons (go/toast-abuse).
  • This means custom toasts are only possible if the app is in the foreground. In the foreground the app has control over its own view hierarchy and is capable of creating any visual elements it would otherwise use custom toasts for.
  • If we were to declare ongoing support for foreground toasts the developer would be in a situation where they either check for foreground status of the app before posting a custom toast or they accept that the information they want to display may not be shown at all. This is not great.
  • There is also a desire to avoid custom toasts altogether since they hurt UX consistency (https://docs.google.com/presentation/d/1r5WEofZ_G3B9M65nS37uD4RqA4iV9HUmngyE6ZpBSsw/edit#slide=id.g7b69852da2_0_0).

Also added a recommendation to use Snackbars while the app is in the foreground.

Toast Abuse - Attack using Android Toast