android自定义toast(widget开发)示例
1、toast控件:
通过查看源代码,发现toast里面实现的原理是通过服务context.layout_inflater_service获取一个layoutinflater布局管理器,从而获取一个view对象(textview),设置内容将其显示
public static toast maketext(context context, charsequence text, int duration) {
toast result = new toast(context);
layoutinflater inflate = (layoutinflater) context.getsystemservice(context.layout_inflater_service);
view v = inflate.inflate(com.android.internal.r.layout.transient_notification, null);
textview tv = (textview)v.findviewbyid(com.android.internal.r.id.message);
tv.settext(text);
result.mnextview = v;
result.mduration = duration;
return result;
}
定义布局文件:
<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<imageview
android:id="@+id/iv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/notification" />
<textview
android:id="@+id/tv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textsize="18sp"
android:text="text"
/>
</linearlayout>
自定义mytoast类:
public class mytoast {
/**
* 显示自定义的土司
* @param context 上下文
* @param iconid 图标的id
* @param text 显示的文本
*/
public static void showtoast(context context,int iconid, string text){
view view = view.inflate(context, r.layout.my_toast, null);
textview tv = (textview) view.findviewbyid(r.id.tv_my_toast);
imageview iv = (imageview) view.findviewbyid(r.id.iv_my_toast);
iv.setimageresource(iconid);
tv.settext(text);
toast toast = new toast(context);
toast.setduration(0);
toast.setview(view);
toast.show();
}
}