android 自定义toast

public class ToastUtils {
    private static Toast toast;

    /**
     * 
     * @param context
     * @param resource  图标
     * @param text  内容
     * @param width   toast宽
     * @param height   toast高
     */
    public static void show(Context context, int resource, String text, int width, int height) {
        if(toast == null) {
            synchronized (ToastUtils.class) {
                if(toast == null) {
                    toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
                }
            }
        }
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.toast, null);
        LinearLayout layout = view.findViewById(R.id.toastLayout);
        int w = dp2px(context, width);
        int h = dp2px(context, height);
        ViewGroup.LayoutParams layoutParams = layout.getLayoutParams();
        layoutParams.height = h;
        layoutParams.width = w;
        layout.setLayoutParams(layoutParams);
        ((TextView) view.findViewById(R.id.text)).setText(text);
        ((ImageView) view.findViewById(R.id.icon)).setImageResource(resource);
        toast.setView(view);
        toast.setGravity(Gravity.BOTTOM, 0, PlatesUtils.dp2px(context, 30));
        toast.show();
    }

    public int dp2px(Context context, float dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
}

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">
    <LinearLayout
        android:id="@+id/toastLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_toast"
        android:gravity="center"
        android:padding="0dp"
        android:layout_margin="0dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="30dp"
            android:layout_height="30dp"/>

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="33sp"
            android:textColor="@color/white"
            android:maxLines="1"/>
    </LinearLayout>

</LinearLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值