Android自定義Toast
Android原生的Toast,看起來灰色的不太好看,我們可以通過下面的自定義Toast的方法來實現自定義Toast的布局和內容
運行結果預覽圖
實現步驟
1.新建 Toast背景 bg_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#FFEB3B"/>
<corners
android:radius="25dp"/>
<padding
android:left="50dp"
android:right="50dp"
android:top="10dp"
android:bottom="10dp"/>
</shape>
2.新建Toast的布局文件 view_toast_custom.xml
<?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">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:background="@drawable/bg_toast"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:id="@+id/tvToast"
android:text="Toast"
android:textSize="35dp"
android:textColor="#fff"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
注:這個是Toast里面的內容,也可以加入圖片,增加Toast的美觀性
3.在MainActivity里面寫一個函數,通過調用實現自定義Toast
public void MyToast(String str, int showTime) {
View view= LayoutInflater.from(this).inflate(R.layout.view_toast_custom,null);
TextView tv_msg = (TextView) view.findViewById(R.id.tvToast);
tv_msg.setText(str);
Toast toast = new Toast(this);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 20);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
}
點擊下載源碼:下載
github下載地址:https://github.com/ldy731729142/ToastDemo