自定义Toast

作者: Ad大成 | 来源:发表于2020-12-28 12:45 被阅读0次

    toast_back

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="@dimen/dp_12"/>
        <solid android:color="@color/colorBG"/>
    </shape>
    

    toast_layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_vertical"
        android:alpha="0.4"
        android:padding="@dimen/dp_20"
        android:background="@drawable/toast_back"
    
        >
        <TextView
            android:id="@+id/toast_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:textColor="@color/white"
            android:gravity="center"
            android:textSize="@dimen/sp_24"/>
    
    </LinearLayout>
    

    MToast

    package com.tencent.wcenter.utils;
    
    import android.animation.ObjectAnimator;
    import android.app.Activity;
    import android.app.Application;
    import android.content.Context;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.tencent.wcenter.R;
    
    public class MToast extends Toast {
        /**
         * Construct an empty Toast object.  You must call {@link #setView} before you
         * can call {@link #show}.
         *
         * @param context The context to use.  Usually your {@link Application}
         *                or {@link Activity} object.
         */
        private static MToast toast;
    
        public MToast(Context context) {
            super(context);
        }
    
        /**
         * 隐藏当前Toast
         */
        public static   void cancelToast() {
            if (toast != null) {
                toast.cancel();
            }
        }
    
        public void cancel() {
            try {
                super.cancel();
            } catch (Exception e) {
    
            }
        }
    
        @Override
        public void show() {
            try {
                super.show();
            } catch (Exception e) {
    
            }
        }
        /**
         * 初始化Toast
         *
         * @param context 上下文
         * @param text    显示的文本
         */
        private static   void initToast(Context context, CharSequence text) {
            try {
                cancelToast();
    
                toast = new MToast(context);
    
    
                // 获取LayoutInflater对象
                LayoutInflater inflater =
                        (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
                // 由layout文件创建一个View对象
                View layout = inflater.inflate(R.layout.toast_layout, null);
    
                // 吐司上的图片
    //            toast_img = (ImageView) layout.findViewById(R.id.toast_img);
    
                // 吐司上的文字
                TextView toast_text = (TextView) layout.findViewById(R.id.toast_text);
                toast_text.setText(text.toString());
                toast.setView(layout);
                toast.setGravity(Gravity.CENTER, 0, 255);
    //            toast.setMargin(0,context.getResources().getDimensionPixelSize(R.dimen.dp_100));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 图标状态 不显示图标
         */
        private static final int TYPE_HIDE = -1;
        /**
         * 图标状态 显示√
         */
        private static final int TYPE_TRUE = 0;
        /**
         * 图标状态 显示×
         */
        private static final int TYPE_FALSE = 1;
    
        /**
         * 显示Toast
         *
         * @param context 上下文
         * @param text    显示的文本
         * @param time    显示时长
         * @param imgType 图标状态
         */
        private static void showToast(Context context, CharSequence text, int time, int imgType) {
            // 初始化一个新的Toast对象
            initToast(context, text);
    
            // 设置显示时长
            if (time == Toast.LENGTH_LONG) {
                toast.setDuration(Toast.LENGTH_LONG);
            } else {
                toast.setDuration(Toast.LENGTH_SHORT);
            }
    
            // 判断图标是否该显示,显示√还是×
    //        if (imgType == TYPE_HIDE) {
    //            toast_img.setVisibility(View.GONE);
    //        } else {
    //            if (imgType == TYPE_TRUE) {
    //                toast_img.setBackgroundResource(R.drawable.toast_y);
    //            } else {
    //                toast_img.setBackgroundResource(R.drawable.toast_n);
    //            }
    //            toast_img.setVisibility(View.VISIBLE);
    
                // 动画
    //            ObjectAnimator.ofFloat(toast_img, "rotationY", 0, 360).setDuration(1700).start();
            // 显示Toast
    
    //        View view = View.inflate(context, R.layout.toast_layout, null);
    //        toast.setView(view);
    //        toast.setGravity(Gravity.CENTER_HORIZONTAL,0,SystemUtils.getWidthPixels(context)/2);
    //        toast.setMargin(0,context.getResources().getDimensionPixelOffset(R.dimen.dp_400));
            toast.show();
        }
    
        /**
         * 显示一个纯文本吐司
         *
         * @param context 上下文
         * @param text    显示的文本
         */
        public static void showText(Context context, CharSequence text) {
            showToast(context, text, Toast.LENGTH_SHORT, TYPE_HIDE);
        }
    
        /**
         * 显示一个带图标的吐司
         *
         * @param context   上下文
         * @param text      显示的文本
         * @param isSucceed 显示【对号图标】还是【叉号图标】
         */
        public static void showText(Context context, CharSequence text, boolean isSucceed) {
            showToast(context, text, Toast.LENGTH_SHORT, isSucceed ? TYPE_TRUE : TYPE_FALSE);
        }
    
        /**
         * 显示一个纯文本吐司
         *
         * @param context 上下文
         * @param text    显示的文本
         * @param time    持续的时间
         */
        public static void showText(Context context, CharSequence text, int time) {
            showToast(context, text, time, TYPE_HIDE);
        }
    
        /**
         * 显示一个带图标的吐司
         *
         * @param context   上下文
         * @param text      显示的文本
         * @param time      持续的时间
         * @param isSucceed 显示【对号图标】还是【叉号图标】
         */
        public static void showText(Context context, CharSequence text, int time, boolean isSucceed) {
            showToast(context, text, time, isSucceed ? TYPE_TRUE : TYPE_FALSE);
        }
    
    
    
    }
    
    
    
    
    

    使用

    package com.tencent.wcenter.utils;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Context;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationManager;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Build;
    import android.telephony.TelephonyManager;
    import android.util.DisplayMetrics;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    
    import com.tencent.jsbridge.LogUtils;
    import com.tencent.wcenter.R;
    import com.tencent.wcenter.app.WCenterApplication;
    
    import java.lang.reflect.Method;
    import java.net.URISyntaxException;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    
    public class SystemUtils {
    
        /**
         * 检查是否有网络
         * @return
         */
        private static String TAG="SystemUtils";
    
    
    
        public static boolean checkNetWork(){
            ConnectivityManager manager = (ConnectivityManager) WCenterApplication.WCenterApplication.getSystemService(Context.CONNECTIVITY_SERVICE);
            return manager.getActiveNetworkInfo() != null;
        }
    
        /**
         * 当前是否是wifi链接
         * @return
         */
        public static boolean isWifiConnected(){
            ConnectivityManager manager = (ConnectivityManager) WCenterApplication.WCenterApplication.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            return info != null;
        }
    
        /**
         * 检查手机(4,3,2)G是否链接
         */
        public static boolean isMobileNetworkConnected(){
            ConnectivityManager manager = (ConnectivityManager) WCenterApplication.WCenterApplication.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            return info != null;
        }
    
        public static long getSystemTime(){
            return System.currentTimeMillis();
        }
    
        /**
         * 获取屏幕的dpi
         * @param at
         * @return
         */
        public static int getDpi(Activity at){
            DisplayMetrics dm = new DisplayMetrics();
            at.getWindowManager().getDefaultDisplay().getMetrics(dm);
            return dm.densityDpi;
        }
    
    
        /**
         * 获取包名
         * @param context
         * @return
         */
        public static String getPgName(Context context){
            return context.getPackageName();
        }
    
        /**
         * 获取版本号
         * @param context
         * @return
         */
        public static Long getVersionCode(Context context, String pg){
            PackageInfo pgInfo = null;
            try {
                pgInfo = context.getPackageManager().getPackageInfo(pg,0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
                return Long.valueOf(pgInfo.versionCode);
            }else{
    
    //            return pgInfo.getLongVersionCode();
                return  null;
    
            }
        }
        /**
         * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
         */
        public static int dp2px(Context context, float dpValue) {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }
    
        public static int dp2px(float dpValue) {
            final float scale = WCenterApplication.WCenterApplication.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }
    
        /**
         * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
         */
        public static int px2dp(Context context, float pxValue) {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (pxValue / scale + 0.5f);
        }
    
        public static int px2dp(float pxValue) {
            final float scale = WCenterApplication.WCenterApplication.getResources().getDisplayMetrics().density;
            return (int) (pxValue / scale + 0.5f);
        }
    
        @SuppressLint("SimpleDateFormat")
        public static String currentTime(long time){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.0");
            Date date = new Date(time);
            return simpleDateFormat.format(date);
        }
    
        public static Integer StringToTimestamp(String time){
    
    
            int times = 0;
            try {
                times = (int) ((Timestamp.valueOf(time).getTime())/1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(times==0){
                LogUtils.i(TAG,"转换时间戳失败");
            }
            return times;
    
        }
        public static String getTypeOfDevice() {
            String value = null;
            try {
                Class<?> clazz = Class.forName("android.os.SystemProperties");
                Method get = clazz.getMethod("get", String.class);
                value = (String) (get.invoke(clazz, "ro.wt.channel"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return value;
        }
    
    
    
        public static boolean checkDomain(String inputUrl,String realWhite)  {
    
            if (inputUrl!=null){
                if (!inputUrl.startsWith("http://")&&!inputUrl.startsWith("https://")&&!inputUrl.startsWith("yy://")&&!inputUrl.startsWith("file://"))
                {
                    return false;
                }
                if (inputUrl.startsWith("yy://")){
                    return true;
                }
                if (inputUrl.startsWith("file://")){
                    return true;
                }
    //        String whiteList1 = ImpWhiteList.getInstance().whiteList;
                LogUtils.i(TAG, "checkDomain: 获取的白名单"+realWhite);
                if (realWhite!=null){
                    String[] split = realWhite.split(",");
                    //此处设置白名单
    //        String[] whiteList=new String[]{"site1.com","site2.com"};
                    java.net.URI url= null;
                    try {
                        url = new java.net.URI(inputUrl);
                    } catch (URISyntaxException e) {
                        return false;
                    }
                    String inputDomain=url.getHost(); //提取host
                    LogUtils.i(TAG, "checkDomain: url_host:"+inputDomain);
                    for (String whiteDomain:split)
                    {
                        if (inputDomain.endsWith(whiteDomain)) //www.site1.com      app.site2.com
                            return true;
                    }
                }
    
    
    
    
            }
    
            return  false;
        }
    
        public static void showToast( Context context, String toastInfoStr ){
    //        Toast.makeText( context, toastInfoStr, Toast.LENGTH_LONG ).show( );
            MToast.showText(context,toastInfoStr);
    
    
    
    
        }
    
        public static int getHeightPixels(Context context){
           return context.getResources().getDisplayMetrics().heightPixels;
        }
    
        public static int getWidthPixels(Context context){
            return context.getResources().getDisplayMetrics().widthPixels;
        }
    
    
        public static boolean isTelephonyCalling(Context context){
            boolean calling=false;
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager.getCallState()==TelephonyManager.CALL_STATE_OFFHOOK||telephonyManager.getCallState()==TelephonyManager.CALL_STATE_RINGING){
                calling=true;
            }
            return  calling;
    
    
        }
    
    
    
        public static void atlastTime(long currentT, long  futureT){
            LogUtils.i(TAG,"最终耗时结果:"+(futureT-currentT));
        }
    
    //    private String getLngAndLat(Context context) {
    //        double latitude = 0.0;
    //        double longitude = 0.0;
    //        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    //        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
    //            @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    //            if (location != null) {
    //                latitude = location.getLatitude();
    //                longitude = location.getLongitude();
    //            } else {//当GPS信号弱没获取到位置的时候又从网络获取
    //                return getLngAndLatWithNetwork();
    //            }
    //        } else {    //从网络获取经纬度
    ////            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
    //            @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    //            if (location != null) {
    //                latitude = location.getLatitude();
    //                longitude = location.getLongitude();
    //            }
    //        }
    //        return longitude + "," + latitude;
    //    }
    
    //    //从网络获取经纬度
    //    public String getLngAndLatWithNetwork() {
    //        double latitude = 0.0;
    //        double longitude = 0.0;
    ////        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    ////        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
    ////        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    //        if (location != null) {
    //            latitude = location.getLatitude();
    //            longitude = location.getLongitude();
    //        }
    //        return longitude + "," + latitude;
    //    }
    }
    

    相关文章

      网友评论

        本文标题:自定义Toast

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