在Android11及以上的版本中Toast中setText方法会引发 java.lang.IllegalStateException: Text provided for custom toast, remove previous setView() calls if you want a text toast instead.
因此需要将原来的 Toast.setText(msg) 替换为 Toast.setView(view)
下面将是我的示例:
public class ToastView { private Toast mToast;
public ToastView(Toast toast) {
this.mToast = toast;
}
public static class Builder {
@LayoutRes
int layout;
FrameLayout.LayoutParams params;
@ColorRes
@DrawableRes
int background;
@ColorRes
int textColor;
public Builder(@LayoutRes int layout) {
this.layout = layout;
}
/**
* @params {@link Toast#setGravity(int, int, int)} 参数分别对应gravity,width,height
*/
public Builder setParams(FrameLayout.LayoutParams params) {
this.params = params;
return this;
}
public Builder setBackground(@ColorRes
@DrawableRes int background) {
this.background = background;
return this;
}
public Builder setTextColor(@ColorRes int textColor) {
this.textColor = textColor;
return this;
}
public ToastView create(Context context) {
Toast mToast = Toast.makeText(context.getApplicationContext(), "", Toast.LENGTH_SHORT);
if (params != null) {
mToast.setGravity(params.gravity, params.width, params.height);
}
View view = LayoutInflater.from(context).inflate(layout, null);
mToast.setView(view);
return new ToastView(mToast);
}
}
public void show(int msg) {
if (mToast == null) {
return;
}
mToast.cancel();
// 检查当前系统版本是否是 Android 11 或更高
if (Build.VERSION.SDK_INT >= 30) {
// Android 11 和更高版本的处理
TextView textView = mToast.getView().findViewById(android.R.id.message);
textView.setText(msg);
mToast.setView(mToast.getView());
} else {
// 对于 Android 10 及以下版本的处理
mToast.setText(msg);
}
mToast.show();
}
public void show(String msg) {
if (mToast == null) {
return;
}
mToast.cancel();
// 检查当前系统版本是否是 Android 11 或更高
if (Build.VERSION.SDK_INT >= 30) {
// Android 11 和更高版本的处理
TextView textView = mToast.getView().findViewById(android.R.id.message);
textView.setText(msg);
mToast.setView(mToast.getView());
} else {
// 对于 Android 10 及以下版本的处理
mToast.setText(msg);
}
mToast.show();
}
public void cancel() {
if (mToast == null) {
return;
}
mToast.cancel();
}
public void release() {
cancel();
Skin.dynamicRemoveView(mToast.getView());
Skin.dynamicRemoveView(mToast.getView().findViewById(android.R.id.message));
mToast = null;
}
} 接下来就是水字数环节 不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班…不想上班… 今天周二,看到这篇文章的人需要V我25