先上自定义Toast的效果图
熟悉qq的同学一定很熟悉这个吐司,我也是高仿了一下。
布局文件item_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/toast_bg"
android:gravity="center"
android:orientation="horizontal"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<ImageView
android:id="@+id/iv"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="8dp"
android:src="@drawable/common_alert_icon" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textColor="#FFF"
android:text="最多只能选取6张照片"/>
</LinearLayout>
</RelativeLayout>
背景:toast_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#aa000000" />
<corners android:radius="10dp" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
AlertToast.java
package com.org.sleepgod.widget;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.org.sleepgod.R;
/**
* 打印自定义Toast
* Created by cool on 2016/10/20.
* 说明:http://blog.csdn.net/cool_fuwei/article/details/52876263
*/
public class AlertToast {
private volatile static AlertToast mAlertToast;
private Toast mToast;
private AlertToast() {
}
/**
* 懒汉单例模式
* @return
*/
public static AlertToast getInstance() {
if (mAlertToast == null) {
synchronized (AlertToast.class) {
if(mAlertToast == null) {
mAlertToast = new AlertToast();
}
}
}
return mAlertToast;
}
/**
* 打印Toast
* @param context
* @param msg
*/
public void showToast(Context context, String msg){
if (mToast == null) {
synchronized (AlertToast.class) {
if(mToast == null) {
mToast = new Toast(context);
}
}
}
View layout = LayoutInflater.from(context).inflate(R.layout.item_toast,null);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(msg);
mToast.setGravity(Gravity.TOP, 0, 0);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.setView(layout);
mToast.show();
}
}
public void click(View v){
AlertToast toast = AlertToast .getInstance();
toast.showToast(this, "最多选只能选取6张照片");
}
使用到的图片资源:<---图片位置,资源图一张透明的图片,这里看的不是很明显,不过可以下下来