Toast工具类

1 toast在子线程中无法直接显示
2 在service中进行显示的时候会报已经存在looper的错误

所以对toast进行了下面的封装

public class ToastUtil {
    private static final String TAG = "ToastUtil";
   
    public static void  customerToastShort(String msg){
       if(!isMainThread()){
           Looper.prepare();
           showShortToast(msg);
           Looper.loop();
       }else {
           showShortToast(msg);
       }

    }

    private static void showShortToast(String msg) {
        Toast toast = Toast.makeText(ThinkDriveApplication.getContext(),
                msg, Toast.LENGTH_SHORT);
//        toast.setGravity(Gravity.CENTER, 50, 50);
        toast.getView().setPadding(15, 15, 15, 15);
        toast.getView().setBackgroundColor(Color.DKGRAY);
        TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
        text.setTextColor(Color.WHITE);
//        text.setTextSize(14);
        toast.show();
    }

    public static void  customerToastLong(String msg){
        if(!isMainThread()){
            Looper.prepare();
            showToastLong(msg);
            Looper.loop();
        }else {
            showShortToast(msg);
        }

    }

    private static void showToastLong(String msg) {
        Toast toast = Toast.makeText(ThinkDriveApplication.getContext(),
                msg, Toast.LENGTH_LONG);
//        toast.setGravity(Gravity.CENTER, 50, 50);
        toast.getView().setPadding(15, 15, 15, 15);
        toast.getView().setBackgroundColor(Color.DKGRAY);
        TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
        text.setTextColor(Color.WHITE);
//        text.setTextSize(14);
        toast.show();
    }

    public static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

}

在service中显示toast,放入子线程中,或者写作这个方法里面

    private void test(String msg){
        
        Handler handler = new Handler(getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                ToastUtil.customerToastShort(msg);
            }
        });
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值