首先自定义Toast 布局:
custom_toast.xml
<?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:background="@android:color/darker_gray"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="14sp" />
</LinearLayout>
自定义toast 背景:
bg_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#000000"/>
<corners
android:radius="15dp"/>
</shape>
自定义Toast:
ToastUtils.java
public class ToastUtils {
public static void showToast(Context context, String toastText,int duration) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_toast, null);
TextView textView = view.findViewById(R.id.text);
textView.setText(toastText);
Toast toast = new Toast(context);
toast.setDuration(duration);
toast.setGravity(Gravity.CENTER, 0, 0);
view.setBackground(ResourcesCompat.getDrawable(context.getResources(), R.drawable.bg_toast, null));
toast.setView(view);
toast.show();
}
}
用法:
ToastUtils.showToast(context, context.getString(R.string.license_expire), 5000);