顯示圖片的(自定義)吐司Toast


一般我們提示的時候都是直接提示文字的,其實Toast也可以顯示圖片

常用方法

  1. Toast.makeText(context,text,duration)這返回一個Toast對象
  2. toast.setDureation(duration)設置持續時間
  3. toast.setGravity(gravity,xOffest,yOffset)設置Toast的位置
  4. toast.setText(s);設置內容
  5. toast.show()顯示內容
  6. toast.setView(View v)

例子

1.只顯示圖片的Toast

 public void showToast(){
      //獲取一個Toast對象,為下面操作准備
      Toast toast = new Toast(this);
      ImageView img = new ImageView(this);
          //用系統提供的圖片
      img.setImageResource(R.drawable.ic_launcher);
          //設置圖片
      toast.setView(img);
      toast.show();        
 }
最后給一個按鈕設定一個監聽器,在onClick方法中調用對應的showToast方法就可以了。(下面兩個例子同樣省略這一步)

2.顯示圖片和文字

public void showToast2(){
      Toast toast = Toast.makeText(this, "這是一個有圖片的吐司", Toast.LENGTH_LONG);
      ImageView img = new ImageView(this);
      img.setImageResource(R.drawable.ic_launcher);
          //得到toast的布局對象
      LinearLayout toast_layout = (LinearLayout) toast.getView();
      //為toast添加圖片資源,第二個參數,0表示圖片在上
      toast_layout.addView(img,1);
      toast.show();
 }

3.設計自己的Toast

有時候上面兩種還沒能滿足自己的要求,就可以自定義布局(我在drawable中放了兩張圖片,詹姆斯和庫里的)

准備布局文件

准備好你想要展示的Toast布局文件,我在layout文件夾新建了一個toast.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="horizontal">
 6     <ImageView
 7         android:layout_width="50dp"
 8         android:layout_height="90dp"
 9         android:background="@drawable/c2"
10         />
11     <TextView
12         android:layout_width="wrap_content"
13         android:layout_height="90dp"
14         android:gravity="center"
15         android:text="VS"
16         />
17     <ImageView        
18         android:layout_width="50dp"
19         android:layout_height="90dp"
20         android:background="@drawable/c1"
21         />     
22 </LinearLayout>

加載你的布局到Toast對象

public void showMyTosat(){
    //把一個布局變成一個View對象
    LayoutInflater inflater = LayoutInflater.from(this);
    View toast_layout = inflater.inflate(R.layout.toast, null);
    Toast toast = new Toast(this);
    //把獲取到的View對象作為setView的參數
    toast.setView(toast_layout);
    toast.show();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM