Toast.makeText(訊息模式)的幾種用法
阿新 • • 發佈:2019-01-30
詳細說來,一共五種用用法。
預設的顯示
自定義位置顯示(值改變位置)
帶圖片顯示(能夠顯示一個圖示)
完全自定義顯示
在其他執行緒中呼叫顯示
該方法的一般用法:
Toast toast = Toast.makeText(context, “”, time);
這三個引數分別是:
1.當前的上下文環境;(getApplicationContext這個方法可以獲取)
2.要顯示的字串;(就是一般的字串,可以寫在string.xml中)
3.顯示的時間長短;(有toast預設的引數,也可以自己設定)
// 第一個引數:當前的上下文環境。可用getApplicationContext()或this
// 第二個引數:要顯示的字串。也可是R.string中字串ID
// 第三個引數:顯示的時間長短。Toast預設的有兩個LENGTH_LONG(長)和LENGTH_SHORT(短),也可以使用毫秒如2000ms
Toast toast=Toast.makeText(getApplicationContext(), "預設的Toast", Toast.LENGTH_SHORT);
//顯示toast資訊
toast.show();
自定義位置
Toast toast=Toast.makeText(getApplicationContext(), "自定義顯示位置的Toast", Toast.LENGTH _SHORT);
//第一個引數:設定toast在螢幕中顯示的位置。我現在的設定是居中靠頂
//第二個引數:相對於第一個引數設定toast位置的橫向X軸的偏移量,正數向右偏移,負數向左偏移
//第三個引數:同的第二個引數道理一樣
//如果你設定的偏移量超過了螢幕的範圍,toast將在螢幕內靠近超出的那個邊界顯示
toast.setGravity(Gravity.TOP|Gravity.CENTER, -50, 100);
//螢幕居中顯示,X軸和Y軸偏移量都是0
//toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
自定義圖片
Toast toast=Toast.makeText (getApplicationContext(), "顯示帶圖片的toast", 3000);
toast.setGravity(Gravity.CENTER, 0, 0);
//建立圖片檢視物件
ImageView imageView= new ImageView(getApplicationContext());
//設定圖片
imageView.setImageResource(R.drawable.ic_launcher);
//獲得toast的佈局
LinearLayout toastView = (LinearLayout) toast.getView();
//設定此佈局為橫向的
toastView.setOrientation(LinearLayout.HORIZONTAL);
//將ImageView在加入到此佈局中的第一個位置
toastView.addView(imageView, 0);
toast.show();
完全自定義
//Inflater意思是充氣
//LayoutInflater這個類用來例項化XML檔案到其相應的檢視物件的佈局
LayoutInflater inflater = getLayoutInflater();
//通過制定XML檔案及佈局ID來填充一個檢視物件
View layout = inflater.inflate(R.layout.custom2,(ViewGroup)findViewById(R.id.llToast));
ImageView image = (ImageView) layout.findViewById(R.id.tvImageToast);
//設定佈局中圖片檢視中圖片
image.setImageResource(R.drawable.ic_launcher);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
//設定標題
title.setText("標題欄");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
//設定內容
text.setText("完全自定義Toast");
Toast toast= new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER , 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
在其他執行緒中通過Handler呼叫
//呼叫方法1
//Thread th=new Thread(this);
//th.start();
//呼叫方法2
handler.post(new Runnable() {
@Override
public void run() {
showToast();
}
});
public void showToast(){
Toast toast=Toast.makeText(getApplicationContext(), "Toast在其他執行緒中呼叫顯示", Toast.LENGTH_SHORT);
toast.show();
}
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
int what=msg.what;
switch (what) {
case 1:
showToast();
break;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
public void run() {
handler.sendEmptyMessage(1);
}