Toast 是一個 View 視圖,快速的爲用戶顯示少許的信息。 Toast 在應用程序上浮動顯示信息給用戶,它永遠不會得到焦點,不影響用戶的輸入等操做,主要用於 一些幫助 / 提示。
Toast 最多見的建立方式是使用靜態方法 Toast.makeTextweb
1. 默認的顯示方式ide
1 // 第一個參數:當前的上下文環境。可用getApplicationContext()或this 2 // 第二個參數:要顯示的字符串。也但是R.string中字符串ID 3 // 第三個參數:顯示的時間長短。Toast默認的有兩個LENGTH_LONG(長)和LENGTH_SHORT(短),也能夠使用毫秒如2000ms 4 Toast toast=Toast.makeText(getApplicationContext(), "默認的Toast", Toast.LENGTH_SHORT); 5 //顯示toast信息 6 toast.show();
2. 自定義顯示位置佈局
1 Toast toast=Toast.makeText(getApplicationContext(), "自定義顯示位置的Toast", Toast.LENGTH_SHORT); 2 //第一個參數:設置toast在屏幕中顯示的位置。我如今的設置是居中靠頂 3 //第二個參數:相對於第一個參數設置toast位置的橫向X軸的偏移量,正數向右偏移,負數向左偏移 4 //第三個參數:同的第二個參數道理同樣 5 //若是你設置的偏移量超過了屏幕的範圍,toast將在屏幕內靠近超出的那個邊界顯示 6 toast.setGravity(Gravity.TOP|Gravity.CENTER, -50, 100); 7 //屏幕居中顯示,X軸和Y軸偏移量都是0 8 //toast.setGravity(Gravity.CENTER, 0, 0); 9 toast.show();
3. 帶圖片的post
1 Toast toast=Toast.makeText(getApplicationContext(), "顯示帶圖片的toast", 3000); 2 toast.setGravity(Gravity.CENTER, 0, 0); 3 //建立圖片視圖對象 4 ImageView imageView= new ImageView(getApplicationContext()); 5 //設置圖片 6 imageView.setImageResource(R.drawable.ic_launcher); 7 //得到toast的佈局 8 LinearLayout toastView = (LinearLayout) toast.getView(); 9 //設置此佈局爲橫向的 10 toastView.setOrientation(LinearLayout.HORIZONTAL); 11 //將ImageView在加入到此佈局中的第一個位置 12 toastView.addView(imageView, 0); 13 toast.show();
4. 徹底自定義顯示方式this
1 //Inflater意思是充氣 2 //LayoutInflater這個類用來實例化XML文件到其相應的視圖對象的佈局 3 LayoutInflater inflater = getLayoutInflater(); 4 //經過制定XML文件及佈局ID來填充一個視圖對象 5 View layout = inflater.inflate(R.layout.custom2,(ViewGroup)findViewById(R.id.llToast)); 6 7 ImageView image = (ImageView) layout.findViewById(R.id.tvImageToast); 8 //設置佈局中圖片視圖中圖片 9 image.setImageResource(R.drawable.ic_launcher); 10 11 TextView title = (TextView) layout.findViewById(R.id.tvTitleToast); 12 //設置標題 13 title.setText("標題欄"); 14 15 TextView text = (TextView) layout.findViewById(R.id.tvTextToast); 16 //設置內容 17 text.setText("徹底自定義Toast"); 18 19 Toast toast= new Toast(getApplicationContext()); 20 toast.setGravity(Gravity.CENTER , 0, 0); 21 toast.setDuration(Toast.LENGTH_LONG); 22 toast.setView(layout); 23 toast.show();
5. 其餘線程經過 Handler 的調用spa
1 //調用方法1 2 //Thread th=new Thread(this); 3 //th.start(); 4 //調用方法2 5 handler.post(new Runnable() { 6 @Override 7 public void run() { 8 showToast(); 9 } 10 });
1 public void showToast(){ 2 Toast toast=Toast.makeText(getApplicationContext(), "Toast在其餘線程中調用顯示", Toast.LENGTH_SHORT); 3 toast.show(); 4 }
1 Handler handler=new Handler(){ 2 @Override 3 public void handleMessage(Message msg) { 4 int what=msg.what; 5 switch (what) { 6 case 1: 7 showToast(); 8 break; 9 default: 10 break; 11 } 12 13 super.handleMessage(msg); 14 } 15 };
1 @Override 2 public void run() { 3 handler.sendEmptyMessage(1); 4 }