自定义toast

来源:互联网 发布:bernsen二值化算法 编辑:程序博客网 时间:2024/06/14 22:31
** * Toast 显示工具类 *  *  */public class ToastUtil {   Context context;   /**    * 弹出短时间toast    *     * @param str    *            显示的内容    */   public static void shortToast(Context context, String str) {      showToast(context, str);   }   /**    * 弹出长时间的toast    *     * @param str    *            显示的内容    */   public static void longToast(Context context, String str) {      if(toast==null){         toast = new Toast(context);      }      View layout = LayoutInflater.from(context).inflate(R.layout.act_my_toast,null);      TextView text = (TextView) layout.findViewById(R.id.tv_toast_text);      text.setText(str);
//下面一行代码是设置toast的位置,有三个参数(第一个toast的位置,第二个x轴,第三个是y轴)//我的需要是距底部110dp
 toast.setGravity(Gravity.BOTTOM, 0, DensityUtil.dip2px(context, 110)); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } private static Toast toast; /** * @param str */ public static void showToast(Context context ,String str){ if(toast==null){ toast = new Toast(context); } View layout = LayoutInflater.from(context).inflate(R.layout.act_my_toast,null); TextView text = (TextView) layout.findViewById(R.id.tv_toast_text); text.setText(str);
//下面一行代码是设置toast的位置,有三个参数(第一个toast的位置,第二个x轴,第三个是y轴)
//我的需要是距底部110dp
 
toast.setGravity(Gravity.BOTTOM, 0, DensityUtil.dip2px(context, 110)); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); }

DensityUtil是我封装的工具类
/** * 根据手机的分辨率 dp(相对单位) 转成 px(像素) */public static int dip2px(Context context, float dpValue) {   final float scale = context.getResources().getDisplayMetrics().density;   return (int) (dpValue * scale + 0.5f);}布局文件act_my_toast,根据自己的需求改就行
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:layout_marginLeft="60dp"        android:layout_marginRight="60dp"        android:id="@+id/tv_toast_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textColor="#ffffff"        android:lineSpacingExtra="6dp"        android:textSize="15dp"        android:gravity="center"        android:background="@drawable/shape_my_toast"/></LinearLayout>背景shape_my_toast,这个根据自己的需求自己设置
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    android:shape="rectangle">    <solid android:color="#000000"/>    <corners android:radius="3dp"/>    <padding android:bottom="15dp"        android:top="15dp"        android:right="15dp"        android:left="15dp"/></shape>
toast也可以设置toast居中显示


0 0
原创粉丝点击