自定义Toast

项目中会经常用到Toast,为了满足项目的整体风格,往往会自定义Toast。今天就实现一个简单的自定义Toast

思路:1.继承Toast类,重写构造方法;

    2.实现一个makeTest(Context context ,CharSequence text ,int duration)方法,返回Toast。具体实现:通过LayoutInflater将一个layout生成view对象

具体代码:

public class MyToast extends Toast{

    private static Toast mToast;

    public MyToast(Context context) {
        super(context);
    }

    public static Toast makeText(Context context  ,CharSequence text ,int duration){

        if(mToast!=null){
            mToast.cancel();
        }

        mToast=new Toast(context);
//        获取LayoutInflater
        LayoutInflater inflater=LayoutInflater.from(context);
//        由layout创建一个view对象
        View layout;

        layout=inflater.inflate(R.layout.custom_my_toast,null);
        TextView contentTextView= (TextView) layout.findViewById(R.id.tv_content);
        contentTextView.setText(text);

        mToast.setView(layout);
        mToast.setDuration(duration);

        return mToast;
    }
}
背景的圆角是通过drawable配置文件实现
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#ed6900"/>
    <corners android:radius="6dip"/>
    <padding android:bottom="0dip"
        android:left="0dip"
        android:right="0dip"
        android:top="0dip"/>
</shape>
自定义toast对应的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_custom_toast">
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dip"
        android:layout_marginBottom="4dip"
        android:layout_marginRight="8dip"
        android:layout_marginLeft="8dip"
        android:textSize="18sp"
        android:gravity="center"
        android:textColor="#ffffff"/>
</LinearLayout>
使用非常简单,
  MyToast.makeText(MainActivity.this ,"贱人薇薇" , Toast.LENGTH_SHORT).show();


有不清楚的地方欢迎留言!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值