android自带的toast样式很多时候和我们的需求不符,所以要自定义一个toast。
一、toast默认的效果,位于app的底部。
Toast.makeText(getApplicationContext(), "test",
Toast.LENGTH_SHORT).show();
二、改变toast的位置
Toast toast =Toast.makeText(getApplicationContext(), "test",
Toast.LENGTH_SHORT);
//xOffset ,yOffset 是指离screen的距离 Toast提示的位置xOffset:大于0向右移,小于0向左移
toast.setGravity(Gravity.CENTER, 20, 40);
toast.show();
三、带图片效果
Toast toast = Toast.makeText(getApplicationContext(),
"带图片的Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.ic_launcher);
toastView.addView(imageView, 0);
toast.show();
四:自定义toast
public static void showToast(Context context,CharSequence text,int duration){
if(mToast == null){
mToast =new Toast(context);
mToast.setDuration(duration);
//xOffset ,yOffset Toast提示的位置xOffset:大于0向右移,小于0向左移
mToast.setGravity(Gravity.CENTER, 0, 0);
View view = View.inflate(context, R.layout.toast_layout, null);
tv_toast = (TextView) view.findViewById(R.id.tv_toast);
tv_toast.setText(text);
mToast.setView(view);
// mToast = Toast.makeText(context, text, duration);
}else{
tv_toast.setText(text);
mToast.setDuration(duration);
}
mToast.show();
}
toast_layout.xml布局文件如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/space_5"
android:background="@drawable/failure" >
<TextView
android:id="@+id/tv_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:singleLine="true"
android:layout_centerInParent="true"
style="@style/size14_style"/>
</RelativeLayout>
实际效果: