oast 控件经常被使用,用来显示提示信息等。
- Toast.makeText(LoginActivity.this, "手机号码不能为空",
- Toast.LENGTH_SHORT).show();
但是有时候,我们需要修改Toast中文字的大小,颜色,可能需要加入图片等等,这时,系统默认的就不能满足我们的需要了。怎么办呢?使用自定义Toast。
- View toastRoot = getLayoutInflater().inflate(
- R.layout.mytoast, null);
- ImageView image = (ImageView) toastRoot.findViewById(R.id.my_toast);
- image.setImageResource(resID);
- Toast toast = new Toast(LoginActivity.this);
- toast.setView(toastRoot);
- toast.setGravity(Gravity.CENTER, 0, 50);
- toast.setDuration(Toast.LENGTH_SHORT);
- toast.show();
如上,使用setView方法,将与布局文件关联起来的View,设置给toast。
自定义Toast的布局文件如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/my_toast"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/dzj_popup_grame"/>
- </LinearLayout>