package com.cheng.utils; import android.content.Context; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.Toast; public class UiUtil { static private Toast mToast = null; static public int getScreenWidthPixels(Context context) { DisplayMetrics dm = new DisplayMetrics(); ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay() .getMetrics(dm); return dm.widthPixels; } static public int dipToPx(Context context, int dip) { return (int) (dip * getScreenDensity(context) + 0.5f); } static public float getScreenDensity(Context context) { try { DisplayMetrics dm = new DisplayMetrics(); ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay() .getMetrics(dm); return dm.density; } catch (Exception e) { return DisplayMetrics.DENSITY_DEFAULT; } } public static void toast (Context context, String msg) { if(TextUtils.isEmpty(msg)) return; // 防止Toast重复显示 if (mToast == null) { mToast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); } else { mToast.setText(msg); mToast.setDuration(Toast.LENGTH_SHORT); } mToast.show(); } }