Android 7 取消所有TOAST
时间: 2023-08-05 16:12:03 浏览: 37
要取消所有 Toast,您可以创建一个自定义 Toast 类并在其中设置一个静态变量来跟踪当前 Toast。然后,您可以在所有 Toast 方法中检查该变量并取消任何现有的 Toast。
以下是一个示例:
```
public class CustomToast {
private static Toast currentToast;
public static void showToast(Context context, String message) {
// 取消当前的 Toast
if (currentToast != null) {
currentToast.cancel();
}
// 创建新的 Toast
currentToast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
currentToast.show();
}
}
```
然后,在您的应用程序中,您可以使用 `CustomToast.showToast(context, message)` 方法来显示 Toast,而不是使用 `Toast.makeText()`。
如果您想要取消所有 Toast,只需调用 `CustomToast.showToast(context, "")`。这将显示一个空消息的 Toast,但它将替换任何现有的 Toast。
相关问题
Android 7.0.2自定义Toast显示时间 可以取消
在Android中,可以通过自定义Toast的布局文件和使用Handler来实现自定义Toast显示时间和取消。
首先,创建一个自定义的Toast布局文件,例如:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#CC000000"
android:padding="10dp">
<ImageView
android:id="@+id/toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:src="@drawable/ic_info"/>
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"/>
</LinearLayout>
```
然后,在你的Activity中,使用以下代码创建自定义Toast:
```java
// 获取自定义布局文件
View toastView = LayoutInflater.from(this).inflate(R.layout.custom_toast_layout, null);
// 设置Toast显示的图片和文本
ImageView imageView = toastView.findViewById(R.id.toast_image);
imageView.setImageResource(R.drawable.ic_info);
TextView textView = toastView.findViewById(R.id.toast_text);
textView.setText("This is a custom Toast message.");
// 创建Toast对象
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastView);
// 延迟显示Toast
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.show();
}
}, 2000);
// 取消Toast
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 5000);
```
上述代码中,首先获取自定义布局文件,并设置Toast显示的图片和文本。然后创建Toast对象,并使用Handler来延迟2秒显示Toast,并在5秒后取消Toast。通过调用Toast的cancel()方法可以取消正在显示的Toast。
android studio确认和取消,Android Studio取消Toast消息以显示新消息
您可以在显示新消息之前先取消现有的Toast消息。要实现这个功能,您需要创建一个Toast对象并在需要取消它时调用cancel()方法。以下是示例代码:
```
Toast toast = Toast.makeText(getApplicationContext(), "旧消息", Toast.LENGTH_SHORT);
toast.show();
// 取消旧消息以显示新消息
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(getApplicationContext(), "新消息", Toast.LENGTH_SHORT);
toast.show();
```
这样,您就可以取消旧的Toast消息并显示新的Toast消息。