问题描述
我希望在单元测试中测试我的 Alert toast 类。但是,当我调用 alert_toast.show
时,出现错误 Can't create handler inside thread that has not called Looper.prepare()
。
我知道我无法从工作程序类或其他处理类(例如单元测试)调用 UI 相关元素,例如 Toast。但是,有没有办法在我的单元测试中调用 alert_toast.show
?
我的 alert_toast 类代码
public class Custom_toasts {
private Context context;
private final int TOAST_TEXT_COLOR = R.color.white;
private final int TOAST_TEXT_GraviTY = Gravity.CENTER;
private boolean toast_shown = false;
private Toast toast;
public Custom_toasts(Context context){
this.context = context;
}
public Toast getToast(){
return toast;
}
public void show_toast(String message,int toast_color){
toast_shown = false;
toast = Toast.makeText(context,message,Toast.LENGTH_LONG);
View view = toast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
int background_color = ContextCompat.getColor(context,toast_color);
view.getBackground().setColorFilter((background_color),PorterDuff.Mode.SRC_IN);
//Gets the TextView from the Toast so it can be editted
TextView text = view.findViewById(android.R.id.message);
int string_color = ContextCompat.getColor(context,TOAST_TEXT_COLOR);
text.setTextColor((string_color));
text.setGravity(TOAST_TEXT_GraviTY);
toast.show();
toast_shown = true;
}
public boolean getToast_shown(){
return toast_shown;
}
}
我做了一些研究,大多数答案表明我可以显示吐司,但前提是显示吐司之后我点击了用户界面上的一个按钮,比如点击一个按钮将显示祝酒词。如下所示:(https://gist.github.com/brunodles/badaa6de2ad3a84138d517795f15efc7)。
我不想创建另一个 layout.xml 只是为了测试这个 toast 会在调用 alert_toast.show 时显示。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)