我想创建一个简单的帮助器类,仅显示调试变体的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)
答案 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)