自定义Toast2

本文介绍了一种自定义Toast的方法,并提供了详细的XML布局文件及Java代码实现。通过简单的封装,可以轻松创建带有图标和自定义样式的Toast提示。

看完了网上的自定义Toast,自己进行了一下封装:toast.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#daaa" > <ImageView android:id="@+id/toast_icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp"/> <TextView android:id="@+id/toast_text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#fff" /> </LinearLayout>
java代码:

public class CustomToast extends Toast { private LayoutInflater mLayoutInflater = null; private ImageView mImageView; private TextView mTextView; private Context mContext; public CustomToast(Context context) { super(context); mContext = context; mLayoutInflater = LayoutInflater.from(context); View v = mLayoutInflater.inflate(R.layout.toast, null); mImageView = (ImageView)v.findViewById(R.id.toast_icon); mTextView = (TextView)v.findViewById(R.id.toast_text); this.setGravity(Gravity.CENTER_VERTICAL, 0, 0); setView(v); } public void setText(CharSequence text) { mTextView.setText(text); } public void setText(int id) { String str = mContext.getString(id); setText(str); } public void setImage(int id) { mImageView.setImageResource(id); } public static CustomToast makeToast(Context c, int imageId, String text, int time) { CustomToast toast = new CustomToast(c); toast.setImage(imageId); toast.setText(text); toast.setDuration(time); return toast; } }
使用:

CustomToast.makeToast(this, R.drawable.xxx, "自定义Toast", Toast.LENGTH_LONG).show();

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值