Better Android Toast
According to the project experience, Toast, which comes with Android, is packaged into a simpler tool class.
The main features are as follows: to simplify the long-term and short-term Toast calls, and to add a custom View Toast, only one line of code is needed.
Design sketch:
Toast layout.xml file
<?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/Your own png picture" />
<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 tool 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();
}
}
The kerners BG gray.xml file in the drawable directory can realize the circular and rectangular background.
<?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>
Call method:
T t = new T(this);
t.cool("This is custom Toast", Gravity.TOP, 0, 100, 2000, 0);
t.S("Short-term Toast");
Refer to the open source project:
https://github.com/Ericsongyl/AndroidToastUtil/blob/master/app/src/main/java/com/nicksong/toastutil/util/ToastUtil.java
Thanks to the original author!