步骤
- 自定义toast的样式文件
- 将布局转换为view
- 创建toast对象,并设置view即可
源码
1、MainActivity
Toast toast = new Toast(this);
LayoutInflater inflator = LayoutInflater.from(this);
View view = inflator.inflate(R.layout.toast_layout, null);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
2、toast的样式文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/toastsytle"
android:gravity="center">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image"
android:src="@drawable/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提示信息"
android:textSize="20sp"
android:textColor="#fff"
android:layout_centerInParent="true"
android:layout_toRightOf="@+id/image"/>
</RelativeLayout>
</LinearLayout>
这里background="@drawable/toastsytle" 设置了一个背景圆角效果。setGravity可设置显示位置。
3、toastsytle.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>
补充
在默认效果上添加图片
Toast toast = Toast.makeText(this, "显示对话框", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout linearLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
linearLayout.addView(imageView,0);
toast.show();