关于toast的使用方法总结,程序同一时刻只有一个toast,和toast的样式设置。

工具类:app运行只会显示一个toast

import android.content.Context;
import android.widget.Toast;

/**
 * 只会显示一个toast
 * @author xfchen
 *
 */
public class ToastAlone extends Toast {
 Context context;
 /**
  * 唯一的toast
  */
 private static Toast mToast = null;
 public ToastAlone(Context context) {
  super(context);
  this.context=context;
 }

 /**
  * 显示的可以及时清除
  * @param ctx
  * @param tips
  * @param lastTime
  * @return
  */
 public static Toast showToast(Context ctx, int stringid, int lastTime) {
  if (mToast != null) {
   //mToast.cancel();
  } else {
   mToast = Toast.makeText(ctx, stringid, lastTime);
  }
  mToast.setText(stringid);
  mToast.show();
  return mToast;
 }

 /**
  * 显示的可以及时清除
  * @param ctx
  * @param tips
  * @param lastTime
  * @return
  */
 public static Toast showToast(Context ctx, String tips, int lastTime) {
  if (mToast != null) {
   //mToast.cancel();
  } else {
   mToast = Toast.makeText(ctx, tips, Toast.LENGTH_SHORT);
  }
  mToast.setText(tips);
  mToast.show();
  return mToast;
 }
 /**
  * 显示的可以及时清除
  * @param ctx
  * @param tips
  * @param lastTime
  * @return
  */
 public static Toast showToast(Context ctx, String tips) {
  if (mToast != null) {
   //mToast.cancel();
  } else {
   mToast = Toast.makeText(ctx, tips, Toast.LENGTH_SHORT);
  }
  mToast.setText(tips);
  mToast.show();
  return mToast;
 }

}


toast的样式设置,设置自己定义的view。
1.设置toast显示的位置,和toast(吐司)上面的文字的颜色,如何设置。
private void midToast(String str, int showTime)
 {
     Toast toast = Toast.makeText(MainActivity.this, str, showTime);            
     toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL , 0, 0);  //设置显示位置
     TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
     v.setTextColor(Color.YELLOW);     //设置字体颜色
     toast.show();  
 }



2.设置toast的自定义view.可以设置其它view(控件),例如button和图片,textview。等等
private void customToast(String str, int showTime) {
 LayoutInflater inflater = getLayoutInflater();
 View view = inflater.inflate(R.layout.view_toast_custom,  
(ViewGroup) findViewById(R.id.lly_toast)); 
ImageView img_logo = (ImageView) view.findViewById(R.id.img_logo); 
TextView tv_msg = (TextView) view.findViewById(R.id.tv_msg); 
tv_msg.setText(str); 
Toast toast = new Toast(mContext); 
 toast.setGravity(Gravity.CENTER, 0, 0); 
 toast.setDuration(Toast.LENGTH_LONG); 
 toast.setView(view); 
 toast.show(); 
 }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值