笔记75--自定义Toast

来源:互联网 发布:免费下载visio软件 编辑:程序博客网 时间:2024/05/18 12:38

部分转自:http://blog.csdn.net/zjbpku/article/details/7930764

一、自定义显示位置

toast=Toast.makeText(getApplicationContext(), "自定义位置", Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER, 100, 200);toast.show();

二、自定义样式,带图片

toast = Toast.makeText(getApplicationContext(), "带图片的Toast", Toast.LENGTH_LONG);//toast.setGravity(Gravity.CENTER, 0, 0);LinearLayout toastView = (LinearLayout) toast.getView();ImageView imageCodeProject = new ImageView(getApplicationContext());imageCodeProject.setImageResource(R.drawable.ic_launcher);toastView.addView(imageCodeProject, 0);toast.show();

三、完全自定义样式

//自定义一个布局view,然后将此view设置到toast中toast = new Toast(getApplicationContext());toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);toast.setDuration(Toast.LENGTH_LONG);toast.setView(view);toast.show();
四、自定义时间

public class Toasts {  private Toast toast;  private Field field;  private Object obj;  private Method showMethod;  private Method hideMethod;  private int time;  public Toasts(Context c, String text,int time) {  toast = Toast.makeText(c, text, time);  toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL,  0, 0);  this.time=time;  reflectionTN();  }  public void show(){  toast.show();  Handler handler = new Handler();  handler.postDelayed(new Runnable() {  @Override  public void run() {  try {  hideMethod.invoke(obj, null);// 调用TN对象的hide()方法,关闭toast  } catch (Exception e) {  e.printStackTrace();  }  }  }, time);  }  private void reflectionTN() {  try {  field = toast.getClass().getDeclaredField("mTN");  field.setAccessible(true);  obj = field.get(toast);  showMethod = obj.getClass().getDeclaredMethod("show", null);  hideMethod = obj.getClass().getDeclaredMethod("hide", null);  } catch (Exception e) {  e.printStackTrace();  }  }  } 
调用:

new Toasts(this, "时间短", 100).show();

五、解决Toast叠加的问题

如果有几个button,每个都弹出Toast,那么这几个button都点击后,这些Toast消息会叠加出现,这样会持续比较长时间。比如,第一个Toast时间1s,第二个1s,这样会造成时间的叠加。

public class ToastShow {  private Context context;  private Toast toast = null;  public ToastShow(Context context) {  this.context = context;  }  public void toastShow(String text) {  if(toast == null){  toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);}else{  toast.setText(text);  }  toast.show();  }  } 
调用时:

ToastShow ts=new ToastShow(getApplicationContext());switch (v.getId()) {case R.id.btn1:ts.toastShow("1");break;case R.id.btn2:ts.toastShow("2");break;case R.id.btn3:ts.toastShow("3");break;}

0 0