效果
步驟
- 自定義toast的樣式文件
- 將布局轉(zhuǎn)換為view
- 創(chuàng)建toast對象邓厕,并設(shè)置view即可
源碼
1草讶、MainActivity
Toast toast = new Toast(this);
LayoutInflater inflator = LayoutInflater.from(this);
View view = inflator.inflate(R.layout.toast_layout, null);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
2洽糟、toast的樣式文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/toastsytle"
android:gravity="center">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image"
android:src="@drawable/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提示信息"
android:textSize="20sp"
android:textColor="#fff"
android:layout_centerInParent="true"
android:layout_toRightOf="@+id/image"/>
</RelativeLayout>
</LinearLayout>
這里background="@drawable/toastsytle" 設(shè)置了一個(gè)背景圓角效果。setGravity可設(shè)置顯示位置堕战。
3坤溃、toastsytle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#21211d"/>
<corners android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"/>
</shape>
補(bǔ)充
在默認(rèn)效果上添加圖片
Toast toast = Toast.makeText(this, "顯示對話框", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout linearLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
linearLayout.addView(imageView,0);
toast.show();