学习了android后会有很多地方用到Toast,有时候根据需要会自定义Toast来实现不同的效果,网上流传很广的一个五种Toast详解,我就不另外写了,附上地址,有需要的可以去看。
一个程序了toast的弹出一般样式是统一的,这里我写了一个自定义toast的方法,用到的时候直接调用,不需要每次都重复写一遍代码。
1,新建一个toast.xml,设置toast需要的布局,下面是我的布局
<pre name="code" class="java"><span style="font-size:12px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:gravity="center_vertical"
android:orientation="vertical" >
<LinearLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:orientation="vertical" >
<ImageView
android:id="@+id/toast_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@drawable/toast_pwd" />
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout></span>
其中下面一串代码是为了规定每次显示的图片的大小统一
<LinearLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:orientation="vertical" >
android:contentDescription="@drawable/toast_pwd"
这里并不是设置背景,而是不写会有警告......
2,新建一个class命名为ToastUtil,并继承Toast,具体代码如下:
<div style="color: rgb(40, 40, 40); font-family: 'Microsoft YaHei'; line-height: 35px; text-align: left;"><span style="font-size:12px;">public class ToastUtil extends Toast {
<span style="white-space:pre"> </span>public ToastUtil(Context context) {
<span style="white-space:pre"> </span>super(context);
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@SuppressLint("InflateParams")
<span style="white-space:pre"> </span>public static Toast makeText(Context context, int resId, CharSequence text, int duration) {
Toast result = new Toast(context);
//获取LayoutInflater对象
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//由layout文件创建一个View对象 ,加载要显示的界面
View layout = inflater.inflate(R.layout.toast, null);
//实例化ImageView和TextView对象
ImageView imageView = (ImageView) layout.findViewById(R.id.toast_iv);
TextView textView = (TextView) layout.findViewById(R.id.toast_text);
//图片和文字都可以在调用时设置
imageView.setImageResource(resId);
textView.setText(text);
//居中显示
result.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
result.setView(layout);
//显示时间
result.setDuration(duration);
return result;
}
}
</span></div>
3,在LoginActivity中调用这个方法
<span style="font-size:12px;">ToastUtil.makeText(LoginActivity.this, R.drawable.toast_login, "不知道填用户名和密码?你傻啊!", Toast.LENGTH_SHORT).show();
ToastUtil.makeText(LoginActivity.this, R.drawable.toast_pwd, "求求你勾选上吧", Toast.LENGTH_SHORT).show();</span>
LoginActivity具体代码看上一篇android学习——SP方法实现用户登录
好了,一个自定义Toast方法就写出来了