Toast工具类封装,自定义toast

public class ToastUtil {
    private static Toast toast;


    public static void showToast(Context context, String text) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        toast.show();
    }
    public static void showCustomToast(Activity activity,String text){
        
        TextView textView=new TextView(activity);
        textView.setText(text);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
        textView.setPadding(dp2px(10),dp2px(10),dp2px(10),dp2px(10));
        GradientDrawable gd=new GradientDrawable();
        gd.setCornerRadius(dp2px(5));//圆角
        gd.setColor(Color.parseColor("#29FFFFFF"));//黑色透明背景
        textView.setBackground(gd);
        Toast toast=new Toast(activity);
        toast.setView(textView);
        toast.setGravity(Gravity.CENTER,0,0);//区中
        toast.show();//显示
    }

    public static int dp2px(float dipValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dipValue, MyApplication.getAppContext().getResources().getDisplayMetrics());
    }

}

猜你喜欢

转载自blog.csdn.net/qq_45372239/article/details/141467690