自定义toast

首先定义一个toast的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8000BBFF"
    android:id="@+id/root"
    android:gravity="center" >
    <ImageView 
        android:id="@+id/mt_iv"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/mt_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is my toast"
        android:textColor="#00BBFF" />

</LinearLayout>

然后自定义你自己的toast类

public class MyToast {
    private View ll;
    private Toast toast;
    public MyToast(){
    }
    public void ToastShow(Context context,String content,int iv_res){
        ll=LayoutInflater.from(context).inflate(R.layout.mytoast,null);
        ImageView iv=(ImageView)ll.findViewById(R.id.mt_iv);
        TextView tv=(TextView)ll.findViewById(R.id.mt_tv);
        iv.setImageResource(iv_res);
        tv.setText(content);
        toast=new Toast(context);//获得toast对象
        toast.setView(ll);//设置toast布局
        toast.setDuration(Toast.LENGTH_SHORT);//显示时间长短
        toast.show();//显示
              //  toast.setGravity(Gravity.TOP|Gravity.LEFT,0,0);
    }
}        

代码中引用:

mt=new MyToast();
mt.ToastShow(EditActivity.this, "保存成功!", R.drawable.camera);//传入你想显示的图片和字符

注意:

toast.setGravity(int a,int x,int y);这里的a指显示中心(上面就是位于父布局的左,上位置),x指相对于这个中心的水平偏移量,y竖直偏移量

原文地址:https://www.cnblogs.com/zzy-frisrtblog/p/5616233.html