自定义Toast

Android中系统自带的Toast都是白色字体,黑色背景的,这样子用久了总感觉不好看,要是想自己定义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;
}
平时我们Toast.makeText(context,"自定义toast",Toast.LENGTH.LONG).show();都是调用这段代码的,可以看到里面有一个布局文件
R.layout.transient_notification

让我们一起去看下这个布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?android:attr/toastFrameBackground">

    <TextView
        android:id="@android:id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.Toast"
        android:textColor="@color/bright_foreground_dark"
        android:shadowColor="#BB000000"
        android:shadowRadius="2.75"
        />

</LinearLayout>
很简单,只有这么一点,就是一个TextView,我们的吐司提示字体颜色由textColor决定,我们的背景由布局的background决定,所以,你要想得到怎么样的自定义Toast,可以直接在这里改变源码,哈哈,当然这种方式不好,最好还是自己写一个工具类来修改,我自己也写了一个ToastUtil工具类,可以修改Toast的字体颜色,整体背景,局部背景,自定义布局等等,下面给出代码可以下载,要是有自己其他需求可以自己添加。

ToastUtil工具类地址:点击打开链接

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值