Android技术知识Android开发程序员

android 自定义Toast

2016-10-13  本文已影响347人  碎念枫子

我们要自定义一个Toast的话肯定要考虑到两点

private static HandlerThread ht;
    static {
        ht = new HandlerThread("download thread");
        ht.start();
    }
    private Handler mHandler = new Handler(ht.getLooper()) {...}

废话不多说、上代码

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>
上一篇下一篇

猜你喜欢

热点阅读