注释都写上了,希望能够帮助上搜索的奋斗者,转载务必注明出处http://blog.csdn.net/u013017597/article/details/17079141
Toast自定义的两种方式见本博客的这篇文章:http://blog.csdn.net/u013017597/article/details/17094319
最定义Toast,在工作中能够起到很好的展示效果
今天刚刚构建了一个代码直接上
private static LinearLayout setToastSelfStyle(Context context, String strText) {
if (linearLayout == null) {
linearLayout = new LinearLayout(context);
}
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
if (mTv == null) {
mTv = new TextView(context);
}
mTv.setText(strText);
mTv.setTextColor(context.getResources().getColor(R.color.beige));
mTv.setTextSize(20);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setBackgroundResource(R.drawable.toast_bg_style);
linearLayout.removeAllViews();
linearLayout.addView(mTv);
return linearLayout;
}
/**
* 通用,吐司提示。显示时长2秒
* @param context
* @param text
*/
public static void showToast(Context context, String text) {
if (toast == null) {
toast = new Toast(context);
}
toast.setView(setToastSelfStyle(context, text)); // 这里只可以String类型的数据
toast.show();
}
上面有个问题就是,想输入id或者文字的时候都需要多执行好几行代码
优化下只变动一行代码就满足id和文字的展示
/**
* 通用,吐司提示。显示时长2秒
* @param context
* @param text
*/
public static void showToast(Context context, String text) {
if (toast == null) {
toast = new Toast(context);
}
if (mTv == null) {
mTv = new TextView(context);
}
mTv.setText(text);
toast.setView(setToastSelfStyle(context));
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
/**
* 自定义样式
* @param context
* @return
*/
private static LinearLayout setToastSelfStyle(Context context) {
if (linearLayout == null) {
linearLayout = new LinearLayout(context);
}
if (mTv == null) {
mTv = new TextView(context);
}
mTv.setTextColor(context.getResources().getColor(R.color.white));
mTv.setTextSize(20);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setBackgroundResource(R.drawable.toast_bg_style);
linearLayout.removeAllViews();
linearLayout.addView(mTv);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
return linearLayout;
}
这样构建了自己定义的背景灰色,字体颜色为白色的Toast,当然这里我们对于布局进行了一个圆角的转换
<?xml version="1.0" encoding="utf-8"?>
<!-- Toast提示背景色 -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><shape>
<gradient android:angle="180" android:endColor="#808080" android:startColor="#808080" />
<stroke android:width="1dip" android:color="#808080" />
<corners android:radius="3dp" />
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
</shape></item>
<!--
gradient 主体渐变 startColor开始颜色,endColor结束颜色 ,angle开始渐变的角度(值只能为90的倍数,0时为左到右渐变,90时为下到上渐变,依次逆时针类推)
stroke 边框 width 边框宽度,color 边框颜色
corners 圆角 radius 半径,0为直角 值越大越圆
padding text值的相对位置
-->
</selector>
注释都写上了,希望能够帮助上搜索的奋斗者,转载务必注明出处http://blog.csdn.net/u013017597/article/details/17079141