Android自定义图文Toast效果_创建图文并存的Toast的方法
程序员文章站
2022-03-01 14:53:32
...
本例子通过自定义Toast效果、可以*调用方法创建图文并存、图片、文字Toast、不再是单一的文字Toast效果了、做为复杂的提示应该是非常有用的、先来看看整个程序的运行效果吧
自定义提示Toast、生成一个图文并存的Toast
public static MyToast makeImgAndTextToast(Context context, Drawable drawable, CharSequence text, int duration) { MyToast result = new MyToast(context); LayoutInflater inflate = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(R.layout.view_tips, null); ImageView img = (ImageView) v.findViewById(R.id.tips_icon); img.setBackgroundDrawable(drawable); TextView tv = (TextView) v.findViewById(R.id.tips_msg); tv.setText(text); result.setView(v); // setGravity方法用于设置位置,此处为垂直居中 result.setGravity(Gravity.CENTER_VERTICAL, 0, 0); result.setDuration(duration); return result; }
生成一个只有文本的自定义Toast
public static MyToast makeTextToast(Context context, CharSequence text, int duration) { MyToast result = new MyToast(context); LayoutInflater inflate = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(R.layout.view_tips, null); TextView tv = (TextView) v.findViewById(R.id.tips_msg); tv.setText(text); result.setView(v); // setGravity方法用于设置位置,此处为垂直居中 result.setGravity(Gravity.CENTER_VERTICAL, 0, 0); result.setDuration(duration); return result; }
生成一个只有图片的自定义Toast
public static MyToast makeImgToast(Context context, Drawable drawable, int duration) { MyToast result = new MyToast(context); LayoutInflater inflate = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(R.layout.view_tips, null); ImageView img = (ImageView) v.findViewById(R.id.tips_icon); img.setBackgroundDrawable(drawable); result.setView(v); // setGravity方法用于设置位置,此处为垂直居中 result.setGravity(Gravity.CENTER_VERTICAL, 0, 0); result.setDuration(duration); return result; }
那么调用方式也比较简单、只要在Activity里面调用就可以了、跟普通的控件调用方式是一样的哈
最后给大家献上源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1gdrcs87 密码: 54q4