自定义Toast

这里写图片描述
Toast在开发过程中的使用频率相对是比较高的,有时候为了美观需要我们自己去自定义如上图的图片加文本的Toast,其实像自定义Dialog一样只需填充View即可。
自定义代码

  /**
     * 自定义Toast
     *
     * @param context 上下文
     * @param content 文本内容
     * @param res     图片
     */
    public static void showToast(Context context, String content, int res) {
        //自定义布局
        View view = LayoutInflater.from(context).inflate(R.layout.layout_toast, null);
        TextView textView = (TextView) view.findViewById(R.id.toast_text);
        textView.setText(content);     
        ImageView img = (ImageView) view.findViewById(R.id.toast_img);
        img.setBackgroundResource(res);
        //创建一个toast对象
        Toast toast = new Toast(context);
        //设置toast显示时间
        toast.setDuration(Toast.LENGTH_SHORT);
        //设置Toast的显示位置
        toast.setGravity(Gravity.CENTER, Gravity.CENTER, Gravity.CENTER);
        //填充Toast
        toast.setView(view);
        //显示toast
        toast.show();
    }

XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="400dp"
    android:layout_height="400dp"
    android:background="@drawable/shape_btn_f5f5f5_bg"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp">

    <ImageView
        android:id="@+id/toast_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/icon_my_gold" />

    <TextView
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="5dp"
        android:textColor="#000000"
        android:textSize="@dimen/y34"
        android:textStyle="bold"
        tools:text="登录成功" />
</LinearLayout>

简单实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值