编码实现

**ToastUtils.java**

publicclassToastUtils{privatestaticToastmToast;publicstaticvoidshowShortText(Stringtext){showText(text,Toast.LENGTH_SHORT);}publicstaticvoidshowLongText(Stringtext){showText(text,Toast.LENGTH_LONG);}publicstaticvoidshowText(Stringtext,intduration){if(TextUtils.isEmpty(text)){return;}TextViewtvText;if(mToast==null){mToast=Toast.makeText(MyApplication.getContext(),"",Toast.LENGTH_SHORT);finalViewtoastLayout=((LayoutInflater)MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.toast_layout,null);tvText=toastLayout.findViewById(R.id.toast_text);mToast.setView(toastLayout);}else{mToast.cancel();mToast=Toast.makeText(MyApplication.getContext(),"",Toast.LENGTH_SHORT);finalViewtoastLayout=((LayoutInflater)MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.toast_layout,null);tvText=toastLayout.findViewById(R.id.toast_text);mToast.setView(toastLayout);}mToast.setDuration(duration);tvText.setText(text);mToast.show();}//普通方法.....publicstaticvoidshowToast(Stringmsg,intduration){mToast=Toast.makeText(MyApplication.getContext(),"",duration);mToast.setText(msg);mToast.show();}}```**toast_layout.xml**```clike<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/toast_root"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/bg_toast"><TextViewandroid:textSize="13.5sp"android:textColor="@color/white"android:paddingLeft="12dp"android:paddingRight="12dp"android:paddingTop="8dp"android:paddingBottom="8dp"android:id="@+id/toast_text"android:layout_gravity="center_horizontal"android:shadowColor="#BB000000"android:shadowRadius="2.75"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

**bg_toast**

<?xmlversion="1.0"encoding="utf-8"?><shapeandroid:shape="rectangle"xmlns:android="http://schemas.android.com/apk/res/android"><cornersandroid:radius="6dp"/><solidandroid:color="#cc555555"/></shape>

使用

ToastUtils.showShortText("1111");

总结

自定义背景效果还是比较简单的,有利于统一机型效果,不是很复杂。主要是从toast源码提供的api我们进行了相应的扩展,容易的实现是建立在对原理的理解与运用上的,多多注重基础,一起前进。