android封装Toast

相信大写程序时都会用到Toast给用户一些提示,当然android本身就有Toast提示,但是我们时常都会对他做一些处理,那么我就下面贴出我封装的好Toast;

public class ToastUtils {

    public static void show(Context context, CharSequence msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }

    public static void onMiddleToast(Context context, CharSequence msg) {
        
        if (context == null || TextUtils.isEmpty(msg))
            return;

        /**
         * 尝试解决Android7.1.1 android.view.WindowManager$BadTokenException
         */

        try{

            Toast toast = Toast.makeText(context,msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_VERTICAL , 0, 0);
            View view = toast.getView();
            view.setBackgroundResource(R.drawable.toast_bg);
            view.setPadding(40, 20, 40, 20);
            TextView v = (TextView) view.findViewById(android.R.id.message);
            v.setTextSize(12);
            v.setTextColor(context.getResources().getColor(android.R.color.white));
            toast.setView(view);
            toast.show();

        }catch (Exception e){

        }
    }

    public static void onMiddleToast(Context context, @StringRes int stringId) {

        Toast toast = Toast.makeText(context,stringId, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER_VERTICAL , 0, 0);
        View view = toast.getView();
        view.setBackgroundResource(R.drawable.toast_bg);
        view.setPadding(40, 20, 40, 20);
        TextView v = (TextView) view.findViewById(android.R.id.message);
        v.setTextSize(12);
        v.setTextColor(context.getResources().getColor(android.R.color.white));
        toast.setView(view);
        toast.show();
    }


    public static void show(Context context, @StringRes int stringId) {
        Toast.makeText(context, stringId, Toast.LENGTH_LONG).show();
    }

    public static void show(View view, CharSequence msg) {
        show(view.getContext(), msg);
    }

    public static void show(View view, @StringRes int stringId) {
        show(view.getContext(), stringId);
    }

}

toast时的背景我也做了处理,怎么自定义也不知道大家知不知道,我就在这里啰嗦一下,直接附图啦
android封装Toast_第1张图片
android封装Toast_第2张图片
下面我贴出我的代码,大家直接贴上自己的工程中就可以用啦


<shape xmlns:android="http://schemas.android.com/apk/res/android">


    <solid android:color="#c3000000"/>
    <corners android:radius="5dp"/>
shape>

你可能感兴趣的:(android封装Toast)