自定义toast

以前用Toast的时候都是直接Toast.makeText,这样直接使用系统自带的Toast,不过并不美观。所以这里我自定义Toast,其实Toast可以假装布局,它有个setView方法。这就是自定义Toast的关键,下面是效果

自定义Toast的布局,mytoast.xml。这里给了根布局一个ID,inflate的时候用的

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/my_toast"
    android:background="#15cc3e">

    <TextView
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="我的自定义"
        android:textSize="16sp"/>

</LinearLayout>
自定义的显示Toast的类。有相关说明。
public class MyToast {

    private static Toast toast=null;
    private Context context=null;

    public MyToast(Context context){
        this.context=context;
    }

    public void show(String string){
        //只要显示新的toast就把旧的退出
        if(toast!=null)
            toast.cancel();
        //(Activity)context实现context转换为activity
        Activity activity= (Activity) context;
        LayoutInflater inflater=activity.getLayoutInflater();
        View view=inflater.inflate(R.layout.mytoast, (ViewGroup) activity.findViewById(R.id.my_toast));
        //这里还可以加载图片等其他布局
        TextView textView= (TextView) view.findViewById(R.id.toast_text);
        textView.setText(string);

        toast=new Toast(context);
        //设置位置
        toast.setGravity(Gravity.CENTER,0,0);
        //设置显示时间
        toast.setDuration(Toast.LENGTH_SHORT);
        //设置自定义的布局
        toast.setView(view);
        toast.show();

        ObjectAnimator animator=ObjectAnimator.ofInt(toast,"translationY",toast.getYOffset(),toast.getYOffset()+40);
        animator.setDuration(1000);
        animator.start();
    }
}
利用cancel方法实现了,然后时候都只有一个Toast显示,即新的Toast显示之前把旧的关闭。这样你的Toast可以显示很多东西。但是不建议显示按钮什么的,因为Toast的点击事件是建议的,虽然是可以实现的,但不能跨应用。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值