Toast在开发过程中的使用频率相对是比较高的,有时候为了美观需要我们自己去自定义如上图的图片加文本的Toast,其实像自定义Dialog一样只需填充View即可。
自定义代码
/**
* 自定义Toast
*
* @param context 上下文
* @param content 文本内容
* @param res 图片
*/
public static void showToast(Context context, String content, int res) {
//自定义布局
View view = LayoutInflater.from(context).inflate(R.layout.layout_toast, null);
TextView textView = (TextView) view.findViewById(R.id.toast_text);
textView.setText(content);
ImageView img = (ImageView) view.findViewById(R.id.toast_img);
img.setBackgroundResource(res);
//创建一个toast对象
Toast toast = new Toast(context);
//设置toast显示时间
toast.setDuration(Toast.LENGTH_SHORT);
//设置Toast的显示位置
toast.setGravity(Gravity.CENTER, Gravity.CENTER, Gravity.CENTER);
//填充Toast
toast.setView(view);
//显示toast
toast.show();
}
XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="400dp"
android:layout_height="400dp"
android:background="@drawable/shape_btn_f5f5f5_bg"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<ImageView
android:id="@+id/toast_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/icon_my_gold" />
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:padding="5dp"
android:textColor="#000000"
android:textSize="@dimen/y34"
android:textStyle="bold"
tools:text="登录成功" />
</LinearLayout>
简单实现。