自定义toast

import android.app.Activity;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * creator gonghaohao
 * class name:ToastUtil
 * created at 2017/10/16 16:32
 * function describe:自定义toast弹框
 * 位置居中,包含图片、文字,自定义背景
 * modify
 */

public class ToastUtil {
    public static void centerToast(final Activity context, String string) {
        RelativeLayout layout = (RelativeLayout) context.getLayoutInflater().inflate(R.layout.layout_custom_toast, null);
        (layout.findViewById(R.id.tvCheckoutWay)).setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.ic_launcher));
        ((TextView) layout.findViewById(R.id.tvPercent)).setText(string);

        Toast toast = new Toast(context);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);//居中
        toast.setView(layout);//setting the view of custom toast layout
        toast.show();
    }
public static void centerPicToast(final Activity context, String string,int pic) {
        RelativeLayout layout = (RelativeLayout) context.getLayoutInflater().inflate(R.layout.layout_custom_toast, null);
        (layout.findViewById(R.id.tvCheckoutWay)).setBackgroundDrawable(context.getResources().getDrawable(pic));
        ((TextView) layout.findViewById(R.id.tvPercent)).setText(string);

        Toast toast = new Toast(context);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setView(layout);//setting the view of custom toast layout
        toast.show();
    }

}
 
  
布局文件:layout_custom_toast



    


        

        
    
toast背景资源文件:toast_bg
 
  


    
    
使用:
ToastUtil.centerToast(MainActivity.this, "我是自定义toast");
ToastUtil.centerPicToast(MainActivity.this, "我是自定义toast",R.mipmap.ic_launcher);

效果图
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
 

你可能感兴趣的:(总结)