您的位置:首页 > 编程语言

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

2013-12-03 13:17 381 查看
自定义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的方式,满足了两种不同的需求,很方便的

【作者一字一句敲出来的,如果转载请注明出处】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: