自定义Toast
2019-11-07 本文已影响0人
Anivia_Hanger
代码:
public class MyToast {
private static MyToastmyMyToast;
private ViewtoastRoot;
private Toasttoast;
private TextViewtv;
private MyToast(Context context) {
toastRoot = ((Activity) context).getLayoutInflater().inflate(R.layout.my_toast, null);
toast =new Toast(context.getApplicationContext());
toast.setView(toastRoot);
tv = (TextView)toastRoot.findViewById(R.id.tv_toast_msg);
}
public static void showToast(Context context, int resid) {
String message = context.getString(resid);
showToast(context, message);
}
public static void showToast(Context context, String message) {
showToast(context, message, Toast.LENGTH_SHORT);
}
private static void showToast(Context context, String message, int length) {
if (myMyToast ==null) {
myMyToast =new MyToast(context);
}
myMyToast.show(message, length);
}
private void show(String message, int length) {
tv.setText(message);
toast.setDuration(length);
toast.show();
}
public static void showLongToast(Context context, int resId) {
String s = context.getString(resId);
showLongToast(context, s);
}
public static void showLongToast(Context context, String s) {
showToast(context, s, Toast.LENGTH_LONG);
}
}
布局:
<?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:layout_gravity="center"
android:gravity="center"
android:background="@drawable/tips">
android:id="@+id/tv_toast_msg"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:text="1234"
android:textSize="35sp"
android:textColor="#FF0C0D13"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
Drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 第一层 -->
<solid android:color="#00a1bd"/>
<corners android:radius="100dp"/>
<size android:height="100dp" android:width="600dp">
<!-- 第二层 -->
<item android:bottom="6dp" android:right="6dp" android:top="6dp" android:left="6dp">
<solid android:color="#00d7fc"/>
<corners android:radius="88dp"/>
</selector>