看完了网上的自定义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();
本文介绍了一种自定义Toast的方法,并提供了详细的XML布局文件及Java代码实现。通过简单的封装,可以轻松创建带有图标和自定义样式的Toast提示。
698

被折叠的 条评论
为什么被折叠?



