Toast

Toast是Android系統提供的一種顯示信息的機制。

在程序中通過它可以使一些短小的信息通知給用戶,這些信息的顯示時間有限且沒有焦點,過一段時間後就會消失並且不佔用屏幕空間。

通過靜態方法makeText()創建一個Toast對象接着調用show()便可將Toast顯示出來,如下所示:

**Toast.makeText(context, text, duration).show();
**

makeText()需要3個parameters:

  1. 第一個參數是Context,即Toast要求的上下文;
  2. 第二個參數是Toast要顯示的文本內容;
  3. 第三個參數是Toast持續顯示時間;
    PS:持續顯示時間有兩個內置常量可以選擇——Toast.LENGTH_SHORT和Toast.LENGTH_LONG.

.
關於Toast的顯示位置
Toast的默認顯示位置爲靠近屏幕的底部

有兩個方法可以設置顯示位置:
方法一:setGravity(int gravity, int xOffset, int yOffset)三個參數分別表示(起點位置,水平向右位移,垂直向下位移)
方法二:setMargin(float horizontalMargin, float verticalMargin)
以橫向和縱向的百分比設置顯示位置,參數均爲float類型(水平位移正右負左,豎直位移正上負下)

關於自定義Toast
你可以在XML裏或者你的Java代碼裏爲你的Toast自定義一個layout接着通過setView的方式將你的layout顯示出來。

下面附上Android官方文檔提供的例子
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>

Java代碼部分:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

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();

最後,要注意的是,如果你沒有一個自定義的layout可以使用,那你必須得用makeText(Context,int,int)來創建這個Toast。

注:知識點參考自Android官方文檔以及《第一行代碼:Android》/郭霖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章