Toast高級(jí)用法之設(shè)置帶圖片的Toast和自定義Toast
雖然google推出了更加美觀實(shí)用的snackBar,但是Toast在某些開發(fā)場(chǎng)景中仍然是最合適的選擇扯俱,所以學(xué)好Toast的用法還是很有必要的锨并,何況這么簡(jiǎn)單:)
Toast的常用方法:
- Toast.makeText(context, text, duration); //返回值為Toast
- toast.setDuration(duration);//設(shè)置持續(xù)時(shí)間,毫秒為單位
- toast.setGravity(gravity, xOffset, yOffset);//設(shè)置toast位置菇晃,xOffset和yOffset分別為X軸和y軸的偏移量
- toast.setText(s);//設(shè)置提示內(nèi)容
- toast.show();//顯示toast
1. 設(shè)置帶圖片的Toast蕉毯。用法十分簡(jiǎn)單,用代碼說明:
Talk is cheap, Let`s code!
用法如下:
//一個(gè)顯示帶圖片的Toast方法
public void ShowToast(){
//創(chuàng)建一個(gè)toast
Toast toast = Toast.makeText(this,"帶圖片的Toast",Toast.LENGTH_SHORT);
//調(diào)用toast.getView()方法肌蜻,強(qiáng)制轉(zhuǎn)換一個(gè)LinearLayout作為view
LinearLayout toast_layout = (LinearLayout)toast.getView();
//定義一個(gè)ImageView
ImageView imageView = new ImageView(this);
//將圖片傳入imageView中
imageView.setImageResource(R.mipmap.ic_launcher);
//將imageView添加到view(toast_layout)中互墓,在imageView后面加上參數(shù)即可改變文字和圖片的相對(duì)位置,比如設(shè)置為addView(imageView,0)即可將文字放在圖片的下面蒋搜。
toast_layout.addView(imageView);
//顯示toast
toast.show();
}
讓后為其綁定點(diǎn)擊事件即可篡撵,這里就不貼出來了。
Demo如下:
帶圖片的Toast
2. 設(shè)置自定義Toast豆挽。同樣十分簡(jiǎn)單育谬,還是用代碼說明。
Talk is cheap, Let`s code!
用法如下:
首先需要定義一個(gè)toast_layout作為自定義toast的view帮哈,代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="自定義toast" />
</LinearLayout>
在toast_layout中我們?cè)O(shè)置了一個(gè)imageView和一個(gè)textView分別用來顯示圖片和toast文字
然后編寫自定義Toast方法膛檀,代碼如下:
//定義一個(gè)自定義顯示toast的方法
public void ShowToast2(){
//使用LayoutInflater方法獲取自定義的toast_layout作為toast的view
LayoutInflater inflater = LayoutInflater.from(this);
View toast_view = inflater.inflate(R.layout.toast_layout,null);
//創(chuàng)建一個(gè)toast,這里需要出入context參數(shù)娘侍,傳入this即可
Toast toast = new Toast(this);
//將toast_layout轉(zhuǎn)換成的view傳入toast.setView();方法中
toast.setView(toast_view);
//顯示toast
toast.show();
}
Demo如下:
自定義Toast
完咖刃。