在任何情况下都显示Toast

时间:2017-04-05 02:03:58

标签: android toast android-toast

我写了这个帮手方法来从任何地方展示吐司。在我将它添加到我的帮助库集合之前,有人可以看一下并说它一切正常吗?

static void showToast(Context ctx, CharSequence msg) {

    Looper mainLooper = Looper.getMainLooper();
    Runnable r = new ToastOnUIThread(ctx, msg);

    boolean onUiThread;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        onUiThread = mainLooper.isCurrentThread();
    } else {
        onUiThread = Thread.currentThread() == mainLooper.getThread();
    }

    if (!onUiThread) {
        if (ctx instanceof Activity) {
            ((Activity) ctx).runOnUiThread(r);
        } else {
            Handler h = new Handler(mainLooper);
            h.post(r);
        }
    } else {
        r.run();
    }
}

这里,ToastOnUIThread类是:

private static class ToastOnUIThread implements Runnable {

    private Context ctx;
    private CharSequence msg;

    private ToastOnUIThread(Context ctx, CharSequence msg) {

        this.ctx = ctx;
        this.msg = msg;
    }

    public void run() {

        Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
    }
};

1 个答案:

答案 0 :(得分:0)

我还没有发现任何问题,但是Context是否是Activity的实例也许并不重要,因为:

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

所以,你只需要它:

Handler h = new Handler(mainLooper);
h.post(r);