android 自定義Toast

我們要自定義一個(gè)Toast的話肯定要考慮到兩點(diǎn)

  • 要保證Toast運(yùn)行在主線程中
  • 我這寫(xiě)代碼是放在Application類中的,放在activity也行,如果需要放到一個(gè)類中,那么handler的使用要注意使用handlerThread
private static HandlerThread ht;
    static {
        ht = new HandlerThread("download thread");
        ht.start();
    }
    private Handler mHandler = new Handler(ht.getLooper()) {...}

廢話不多說(shuō)、上代碼

private Toast toast = null;

Handler displayMessageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj != null) {
                displayToastMessage((String) msg.obj);
            }
            super.handleMessage(msg);
        }
    };
public void displayToastMessage(String message) {
        if (message == null || "".equals(message))
            return;

        if (!isMainThread()) {
            Message msg = new Message();
            msg.obj = message;
            displayMessageHandler.sendMessage(msg);
            return;
        }

        if (toast != null)
            toast.cancel();

        LayoutInflater li = LayoutInflater.from(this);
        View layout = li.inflate(R.layout.toastview, null);
        toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);

        TextView text = (TextView) toast.getView().findViewById(R.id.toastText);
        text.setTextColor(Color.BLACK);
        text.setText(message);
        toast.show();
    }

public boolean isMainThread() {    
      return this.getMainLooper().getThread().equals(Thread.currentThread());
}

布局文件代碼: toastview.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toastRootLayout"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp">
    <LinearLayout 
              android:id="@+id/toastLayout"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="horizontal" 
              android:padding="10dp"
              android:background="#FF909090">             
        <TextView android:id="@+id/toastText"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:textColor="#FFFFFF"
                  android:gravity="center" />
    </LinearLayout>
</LinearLayout>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容