更好用的Android Toast
根据项目经验,对Android自带的Toast打包成了一个更加简单的工具类。
主要特点如下,简化长时,短时的Toast调用,添加自定义View的Toast,只需要一行代码就可调用。
效果图:
toast_layout.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/corners_bg_gray"
android:orientation="vertical"
android:padding="@dimen/margin_10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@drawable/你自己的png图片" />
<TextView
android:id="@+id/toast_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="@dimen/textsize_15sp"/>
</LinearLayout>
T.class工具类
public class T {
private TextView tv;
private View tView;
private Context context;
public T(Context _context) {
context = _context;
}
public void cool(String s, int gravity, int xOffset, int yOffset, int duration, int layoutId) {
Toast t = new Toast(context);
t.setGravity(gravity, xOffset, yOffset);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (layoutId != 0)
tView = Objects.requireNonNull(inflater).inflate(layoutId, null);
else
tView = Objects.requireNonNull(inflater).inflate(R.layout.toast_layout,null);
tv = tView.findViewById(R.id.toast_view);
tv.setText(s);
t.setView(tView);
t.setDuration(duration);
t.show();
}
public void L(String s) {
Toast.makeText(context, s, Toast.LENGTH_LONG).show();
}
public void S(String s) {
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
}
drawable目录下的corners_bg_gray.xml文件,可以实现圆矩形背景。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#F0F0F0" />
<corners android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"/>
</shape>
调用方式:
T t = new T(this);
t.cool("这是自定义Toast", Gravity.TOP, 0, 100, 2000, 0);
t.S("短时Toast");
参考了该开源项目:
https://github.com/Ericsongyl/AndroidToastUtil/blob/master/app/src/main/java/com/nicksong/toastutil/util/ToastUtil.java
对原作者表示感谢!