Android自定义吐司(Toast)

安卓写自定义吐司样式,先查看Toast类的源码:


public static Toast makeText(Context context, CharSequence text, @Duration 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;
    }

以上代码片是安卓的吐司源码,自定义样式,先有一个自己的布局,布局中有一个TextView来展示文字信息。设置一下时间duration。


我的自定义吐司:


/**
 * Created by niyl on 2016/5/30.
 */
public class MyToast {

    public MyToast(Context context,String prompt) {
        Toast toast = new Toast(context);
        toast.setDuration(Toast.LENGTH_SHORT);
        View view = View.inflate(context, R.layout.toast_custom,null);
        TextView tvPrompt = (TextView)view.findViewById(R.id.tv_prompt);
        tvPrompt.setText(prompt);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

}

页面布局补一下:

<?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="fill_parent"
    android:layout_height="wrap_content" 
    android:gravity="center"
    android:background="#808080"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:textSize="16sp"
        android:layout_centerInParent="true"
        android:layout_gravity="center_vertical"
        android:textColor="#ffffff"
        android:id="@+id/tv_msg"
        android:padding="15dp"
        />

</LinearLayout>

我将吐司设置在屏幕中间,并直接调show()方法。这样,吐司对象创建便执行了吐司效果。


效果图:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值