美文网首页Android
Toast封装(2018.10.15)

Toast封装(2018.10.15)

作者: 瑟闻风倾 | 来源:发表于2018-10-15 13:10 被阅读6次

1. ToastUtil类

package com.jack.feiYan2.tool;

import android.content.Context;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * Created by liy on 2018-04-09.
 */

public class ToastUtil {
    private static Toast mToast;//public改为private

    /**
     * 传入文字,在中间显示
     * */
    public static void show(Context context, String text){
        if (mToast == null){
            mToast = Toast.makeText( context, text , Toast.LENGTH_SHORT);
        }else {
            //如果当前Toast没有消失, 直接显示内容,不需要重新设置
            mToast.setText(text);
        }
        mToast.setGravity(Gravity.CENTER , 0 , 0);
        mToast.show();
    }
    /**
     * 传入资源文件,在中间显示
     * */
    public static void show(Context context,int resId){
        if (mToast == null){
            mToast = Toast.makeText( context, resId , Toast.LENGTH_SHORT);
        }else {
            //如果当前Toast没有消失, 直接显示内容,不需要重新设置
            mToast.setText(resId);
        }
        mToast.setGravity(Gravity.CENTER , 0 , 0);
        mToast.show();
    }

    /**
     * 传入文字,带图片
     * */
    public static void showImg( Context context , String text , int resImg){
        if (mToast == null){
            mToast = Toast.makeText( context, text , Toast.LENGTH_SHORT);
        }else {
            //如果当前Toast没有消失, 直接显示内容,不需要重新设置
            mToast.setText(text);
        }
        //添加图片的操作,这里没有设置图片和文字显示在一行的操作呢...
        LinearLayout view = (LinearLayout) mToast.getView();
        ImageView imageView = new ImageView(context);
        imageView.setImageResource(resImg);
        view.addView(imageView);

        mToast.show();
    }

}

2. 调用

ToastUtil.show(activity,activity.getString(R.string.error_result_code));

相关文章

网友评论

    本文标题:Toast封装(2018.10.15)

    本文链接:https://www.haomeiwen.com/subject/lxrfzftx.html