自定义Toast

/**
 * 显示自定义的Toast
 *
 * @param content
 */
public void showToast(String content) {
   //加载自定义Toast布局
   View toastView = LayoutInflater.from(activity).inflate(R.layout.toast_like, null);
   
   //获取屏幕宽和高的像素大小
   DisplayMetrics dm = new DisplayMetrics();
   activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
   int mScreenWidth = dm.widthPixels;
   
   LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mScreenWidth,
      LinearLayout.LayoutParams.MATCH_PARENT);
   TextView tv = (TextView) toastView.findViewById(R.id.tv_content);
   //设置Toast宽高
   tv.setLayoutParams(params);
   tv.setText(content);
   
   //定义一个Toast
   Toast toast = new Toast(activity);
   //设置Toast的位置
   toast.setGravity(Gravity.TOP, 0, Util.dip2px(activity, 44));
   //设置透明度
   tv.setAlpha(0.8f);
   toast.setDuration(Toast.LENGTH_SHORT);
   
   //将toastView设置到创建好的Toast中
   toast.setView(toastView);
   
   //显示toast
   toast.show();
}

注意:Util是一个工具类,里边封装了对不同手机的分辨率的处理,顾名思义,dip2px是将dp转换为对应手机的px,下面是dp和px相互转换的方法

/**
 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
 */
public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

/**
 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
 */
public static int px2dip(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}


你可能感兴趣的:(自定义Toast)