自定義帶圖片的Toast

佈局很簡單就是一個ImageView和TextView橫向排列

1、toast.xml

 

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
              android:layout_width="80dp"  
              android:layout_height="30dp"  
              android:padding="10dp"  
              android:gravity="center"  
              android:background="@drawable/toaststyle"  
              android:orientation="horizontal">  
  
    <ImageView  
        android:layout_width="30dp"  
        android:layout_height="30dp"  
        android:id="@+id/imageView"/>  
  
    <TextView  
        android:id="@+id/message"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_weight="1"  
        android:shadowColor="#bbfcd603"  
        android:shadowRadius="2.75"  
        android:textColor="#ffffff"  
        />  
</LinearLayout>  

2、toaststyle.xml

 

 

<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android">  
    <solid android:color="#21211d" />  
    <corners android:topLeftRadius="10dp"  
             android:topRightRadius="10dp"  
             android:bottomRightRadius="10dp"  
             android:bottomLeftRadius="10dp"/>  
</shape>

3、CustomToast.java  自定義的Toast方法

 

 

public class CustomToast {  
    private static TextView mTextView;  
    private static ImageView mImageView;  
  
    public static void showToast(Context context, String message) {  
        //加載Toast佈局  
        View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast, null);  
        //初始化佈局控件  
        mTextView = (TextView) toastRoot.findViewById(R.id.message);  
        mImageView = (ImageView) toastRoot.findViewById(R.id.imageView);  
        //爲控件設置屬性  
        mTextView.setText(message);  
        mImageView.setImageResource(R.mipmap.ic_launcher);  
        //Toast的初始化  
        Toast toastStart = new Toast(context);  
        //獲取屏幕高度  
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);  
        int height = wm.getDefaultDisplay().getHeight();  
        //Toast的Y座標是屏幕高度的1/3,不會出現不適配的問題  
        toastStart.setGravity(Gravity.TOP, 0, height / 3);  
        toastStart.setDuration(Toast.LENGTH_LONG);  
        toastStart.setView(toastRoot);  
        toastStart.show();  
    }  
}  


代碼很詳細,不用多解釋,這裏只是一個簡單的例子,大家感興趣的可以自己添加喜歡的設計,順便說一下,這裏很多屬性都可以自己抽出來的當成變量的,大家可以根據自己的風格封裝乘工具類使用。當然也可以自定義圖片,設置圖片,這樣更靈活,這裏只是寫個demo就沒寫進來了

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章