使用自己的Toast

年前的时候,静不下心来学东西,看着Toast默认样式不爽,就进去大致看一下它的源码然后自己借用了一下它原来的实现,改了个自定义的Toast。(初学者)
最终完成,弹出Toast的代码这样写:

Toast.makeText(this, "再次返回,退出程序", Toast.LENGTH_SHORT).myShow();

哈哈。方法名可以自定义。
下面是自定义Toast类的代码:

public class Toast {
    //声明Context对象、要弹出的字符串、显示时长
    private static Context context;
    private static String str;
    private static int duraiton;

    //声明时长的两个常量(就是使用原Toast的)
    public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;
    public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT;


    private Toast(Context context, String str, int duraiton){
        Toast.context = context;
        Toast.str = str;
        Toast.duraiton = duraiton;
    }

    public static Toast makeText(Context context, String str, int duraiton){
        return new Toast(context, str, duraiton);
    }

    public void myShow(){
        //注意,这里创建的是原Toast,需要加全包名
        android.widget.Toast toast = new android.widget.Toast(context);

        //定义Toast的样式(在布局文件中)
        View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
        ((TextView)view.findViewById(R.id.my_toast_content)).setText(str);
        //设置view
        toast.setView(view);
        //设置弹出的位置
        //toast.setGravity(Gravity.BOTTOM, 0, 0);

        toast.show();
    }
}

toast_view.xml文件

<?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="wrap_content">
    <TextView
        android:text="111"
        android:id="@+id/my_toast_content"
        android:textColor="#e4d63f"
        android:background="@drawable/toast_shape"
        android:paddingTop="@dimen/padding5"
        android:paddingBottom="@dimen/padding5"
        android:paddingStart="@dimen/padding10"
        android:paddingEnd="@dimen/padding10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

需要注意的一个地方是,自定义样式里的textview是需要我们根据传入的str来进行设置的,在执行toast.setView(view)的时候,只是在toast.show()的时候显示我们传入的view视图,而不进行其他操作。

最后,调用处导包要导自己写的Toast的路径。
/……….后记: 挺好玩的,反正我觉着 :P …………/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值