Android在子线程显示Toast闪退,Can"t toast on a thread that has not called Loop

2022-07-14 13:58:07 浏览数 (2)

新建一个类toastHelp

代码语言:javascript复制
package ink.cik.logininfoapp.eneity;

import android.content.Context;
import android.os.Looper;
import android.widget.Toast;

public class toastHelp {
    static Toast toast = null;

    public static void show(Context context, String text) {
        try {
            if (toast != null) {
                toast.setText(text);
            } else {
                toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
            }
            toast.show();
        } catch (Exception e) {
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }
}

然后需要用的时候直接调用

代码语言:javascript复制
toastHelp.show(LoginActivity.this, responseInfo.getInfo());

0 人点赞