Toast自定义,自定义Toast的两种方式,土司的代码显示


自定义Toast替换系统的显示,代码中发现了有两种方式可以实现

方法一:

直接new布局,然后添加一个TextView实现,总体不涉及id,和布局xml的书写,适合平面化的toast

/**
	 * 自定义样式
	 * @param context
	 * @return
	 */
	private static LinearLayout setToastSelfStyle(Context context) {
		if (linearLayout == null) {
			linearLayout = new LinearLayout(context);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
			lp.setMargins(26,0,26,0);
			linearLayout.setLayoutParams(lp);
			linearLayout.setGravity(Gravity.CENTER);
			linearLayout.setBackgroundResource(R.drawable.toast_bg_style);
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			//linearLayout.setPadding(16, 0, 16, 0); //框大小变化
		}
		linearLayout.removeAllViews();
		linearLayout.addView(mTv);
		return linearLayout;
	}
	/**
	 * 设置文字
	 * @param context
	 */
	private static void setText(Context context) {
		if (mTv == null) {
			mTv = new TextView(context);
			mTv.setTextColor(context.getResources().getColor(R.color.white));
			mTv.setTextSize(20);
		}
	}

最终演示如图:



===============================================

方法二:

使用常见的LayoutInflate来进行,这种可以加载自定义的动画,而且显示效果较多,特殊需求的话可以用得着

LayoutInflater inflater = getLayoutInflater();
   View layout = inflater.inflate(R.layout.custom,
     (ViewGroup) findViewById(R.id.llToast));
   ImageView image = (ImageView) layout
     .findViewById(R.id.tvImageToast);
   image.setImageResource(R.drawable.icon);
   TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
   title.setText("Attention");
   TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
   text.setText("完全自定义Toast");
   toast = new Toast(getApplicationContext());
   toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
   toast.setDuration(Toast.LENGTH_LONG);
   toast.setView(layout);
   toast.show();

加载了一个自定义的布局,然后里面有一个Text,一个ImageView


两张方式实现了我们自定义Toast的方式,满足了两种不同的需求,很方便的


【作者一字一句敲出来的,如果转载请注明出处】


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值