这是我使用自定义吐司处理程序的解决方案。在 m 应用程序中完美运行。
public class CustomToast {
private LayoutInflater inflater;
private Toast toast;
private View customToastLayout;
private TextView LblCustomToast;
public CustomToast() {}
public void showCustomToast(String toastMessage, int toastLength, AppCompatActivity context) {
if(inflater == null) {inflater = context.getLayoutInflater();}
if(customToastLayout == null) {customToastLayout = inflater.inflate(R.layout.toast_layout, (ViewGroup) context.findViewById(R.id.toast_layout_root));}
if(LblCustomToast == null) {LblCustomToast = (TextView) customToastLayout.findViewById(R.id.LblCustomToast);}
LblCustomToast.setText(toastMessage);
if(toast == null) {toast = new Toast(context);}
toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.BOTTOM, 0, DPDensity.getPxFromDP(160, context.getResources()));
toast.setDuration(toastLength);
toast.setView(customToastLayout);
if(toast.getView().isShown()) {toast.cancel();}//Toast is cancelled here if currently showing
toast.show();
}
}
这是 XML 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:paddingRight="15dp"
android:paddingBottom="5dp"
android:orientation="vertical"
android:background="@drawable/custom_toast_bg"
android:gravity="bottom|center"
android:layout_marginBottom="50dp">
<TextView android:id="@+id/LblCustomToast"
android:text="Test"
android:textSize="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/lightLime"
android:layout_gravity="center"
android:gravity="center"/>
</LinearLayout>
这是用法:
customToast = new CustomToast();
customToast.showCustomToast(getString(R.string.your_message), Toast.LENGTH_SHORT, (AppCompatActivity) mainActivityContext);