天天看點

定制自己的Toast通知

在Android系統中,消息提醒有Notification通知欄消息提醒,Dialog對話框消息提示,還有一種就是Toast消息通知。

其中Toast消息通知,它是不擷取焦點,不接受觸摸事件,透明的短時間的友好提示,如網絡逾時,編寫短信儲存到草稿箱等等。

首先我們要使用Toast提示消息

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
           

我們還可以指定顯示消息的位置

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
           

上面說的都是系統預設風格的Toast,如何制作我們自己的Toast呢

那麼第一步就是設計我們自己的布局展示,custom_toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>
           

看API我們看到有Toast類中有setView(View view);這個方法,它就是來自定義View,顯示消息的

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
           

這樣就完成我們自己風格的Toast消息展示,當然上面的布局是很簡單的,大家在自定義的時候可以加入不同的控件,來實作想要的效果