2017-04-05 168 views
-1

我写了这个辅助方法来显示任何地方的吐司。在我将它添加到我的帮助程序库集合之前,是否有人可以看一下并说完全没问题?在任何情况下显示吐司

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(); 
    } 
}; 
+0

在使用此代码时是否发现任何问题,需要帮助解决?因为否则我认为这不是问这个问题的正确地方。无论如何,我没有看到你的代码有任何问题 –

回答

0

我还没有发现任何问题,然而,但也许这并不重要Context是否是活动的实例或不是,因为:

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

所以,你只需要:

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