如何判断android中是否显示任何toast

时间:2018-05-21 04:06:28

标签: android android-espresso android-toast

有没有办法检查android中是否显示Toast消息? 我正在编写一个idlingResource,我想确保在将资源作为空闲状态返回之前,当前没有显示toast。

1 个答案:

答案 0 :(得分:0)

  

创建自定义吐司。

private Toast myToast = nuul; // Create class Level Object to
  

在方法

中添加此代码
String message = "Your Message";
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
     the                    (ViewGroup) findViewById(R.id.custom_toast_container));

TextView text = (TextView) layout.findViewById(R.id.custom_toast_text);
text.setText(Message);

myToast = new Toast(getApplicationContext());
myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.setView(layout);
myToast.show();
  

custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_container"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="8dp"
    android:background="#80000000">

    <TextView
        android:id="@+id/custom_toast_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:enabled="true"
        android:textSize="16dp"
        />
</LinearLayout>
  

如果Toast不为空,则关闭Toast

 if (myToast != null) 
  myToast.cancel(); // Dismiss the toast