本文编写于 165 天前,最后修改于 159 天前,其中某些信息可能已经过时。
这里逐渐收集了本人自己编写的「短代码」和「重复发明轮子(Reinventing the wheel)」。所有的短代码可前往 “时光”-“文章标签”-“短代码” 查看
/**
* @author Administrator
* @year 2019
* @Todo TODO 自定义Toast
* @package_name com.example.shengsaidemo2019.toats
* @project_name 2019ShengSaiDemo
* @file_name DiyToast.java
*/
public class DiyToast {
public static Toast toast;// 新建Toast
public static void showToast(Context context, String string) {
View toastRoot = LayoutInflater.from(context).inflate(
R.layout.my_toast, null, false);
TextView tv = (TextView) toastRoot.findViewById(R.id.TextViewInfo);
if (toast == null) {// 如果当前没有toast正在显示
toast = Toast.makeText(context, string, Toast.LENGTH_SHORT);// 展示Toast
toast.setView(toastRoot);
tv.setText(string);
} else {// 如果有正在显示的toast
toast.setView(toastRoot);
tv.setText(string);
}
toast.show();// 展示Toast
}
}
<?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:layout_height="match_parent"
android:background="@drawable/shaper_toast_show_back"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15sp"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/TextViewInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15sp"
android:layout_marginTop="15sp"
android:text="text"
android:textColor="#fff" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="15sp" />
<solid android:color="#3399FF" />
<stroke
android:width="8sp"
android:color="#70FFFFFF" />
</shape>
在任意Class类中使用如下方法:
DiyToast.showToast(getApplicationContext(), "请输入用户名");