当前位置: 移动技术网 > IT编程>移动开发>Android > android自定义toast(widget开发)示例

android自定义toast(widget开发)示例

2019年07月24日  | 移动技术网IT编程  | 我要评论

重庆证券开户,台湾东森电视台,默默无闻造句

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();
    }
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网