Android Toast提示詳解
阿新 • • 發佈:2019-01-24
Toast介紹
Toast是一個用於在使用者操作後給予簡單的反饋的彈出框,簡單來說就是一個提示框,通過Toast彈出框可以與使用者進行簡單的互動,例如,當你在EditText中輸入一些不合法的資料時,開發者可以通過Toast來提示使用者“輸入資料不合法”,toast訊息會在彈出後自動消失。
1.基本使用
- 例項化一個Toast物件,makeText方法需要三個引數,分別是應用程式上下文,提示的文字資訊,顯示時間。
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context , text, duration);
- 通過show()方法來顯示
toast.show();
或者
Toast.makeText(context, text,duration).show();
2.控制Toast的位置
- Toast位置預設顯示在頁面的底部,水平居中,當然我們可以設定其顯示在其他位置,此時我們可以通過setGravity(int, int, int) 方法來改變這個位置,三個引數分別代表Toast的位置(如Toast.TOP),X座標的偏移量,Y座標的偏移量。例如,我們要設定Toast位於螢幕的左上方,可以這樣寫:
toast.setGravity(Gravity.TOP |Gravity.LEFT, 0, 0);
上面展示了Toast的最基本的使用方法,但是有時我們可能會不僅僅滿足顯示文字資訊,可能會顯示一個佈局檔案,下面我們接著往下看!
3.自定義Toast
如果你需要自定義Toast,可以建立一個自定義佈局(可以通過xml檔案來建立或者通過程式碼來實現),通過Toast的setView(View view)方法來新增顯示此佈局。
一、建立custom_toast.xml檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp"
android:src="@drawable/droid" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="18sp"
android:text="@string/toast_text"/>
</LinearLayout>
二、彈出Toast訊息
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_SHORT);
toast.setView(layout);
toast.show();
三、執行效果