仅在调试变体上显示的Toast

时间:2015-08-07 17:58:26

标签: android toast

我想创建一个简单的帮助器类,仅显示调试变体的Toast消息。

像这样使用:

TOAST.makeText(context, "Debug Toast message", Toast.LENGTH_SHORT).show();

TOAST.java

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.mypp.BuildConfig;

/**
 * Toast that only shows for debug build variants.
 */
@SuppressLint("ShowToast")
public class TOAST extends Toast {
    public TOAST(Context context) {
        super(context);
    }

    @NonNull
    public static TOAST makeText(@NonNull Context context, CharSequence text, int duration) {
        return (TOAST) Toast.makeText(context, text, duration);
    }

    @NonNull
    public static TOAST makeText(@NonNull Context context, int resId, int duration) {
        return (TOAST) Toast.makeText(context, resId, duration);
    }

    @Override public void show() {
        if (BuildConfig.DEBUG) {
            super.show();
        }
    }
}

虽然演员在我的实施中失败了:

Caused by: java.lang.ClassCastException: android.widget.Toast cannot be cast to com.mypp.helpers.TOAST
            at com.mypp.helpers.TOAST.makeText(TOAST.java:23)

2 个答案:

答案 0 :(得分:8)

您不能将Toast(基类)的实例类型化为派生类TOAST,但可以采用其他方式。

我建议您将实施更改为以下内容:

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.mypp.BuildConfig;

/**
 * Toast that only shows for debug build variants.
 */
@SuppressLint("ShowToast")
public class TOAST {

    private Toast toast;

    public TOAST(Toast toast) {
        this.toast = toast;
    }

    @NonNull
    public static TOAST makeText(@NonNull Context context, CharSequence text, int duration) {
        return new TOAST(Toast.makeText(context, text, duration));
    }

    @NonNull
    public static TOAST makeText(@NonNull Context context, int resId, int duration) {
        return new TOAST(Toast.makeText(context, resId, duration));
    }

    public void show() {
        if (BuildConfig.DEBUG) {
            toast.show();
        }
    }
}

答案 1 :(得分:0)

思考'组成继承',我相信我们可以找到一个更简单的解决方案。 公共类DebugToast {     public static class Builder {         私人决赛敬酒;         public Builder(Context context,String message,int length){             toast = Toast.makeText(context,message,length);         }         public Builder(Context context,@ StringRes int message,int length){             toast = Toast.makeText(context,message,length);         }         public void show(){             if(BuildConfig.DEBUG)toast.show();         }     }     public static Builder makeText(Context context,String message,int length){         返回新的Builder(上下文,消息,长度);     }     public static Builder makeText(Context context,@ StringRes int message,int length){         返回新的Builder(上下文,消息,长度);     } }