当为Toast使用setDuration()时,是否可以设置一个自定义长度或至少比Toast. length_long更长的长度?
当前回答
如果你深入挖掘android代码,你会发现这些行清楚地表明,我们不能改变Toast消息的持续时间。
NotificationManagerService.scheduleTimeoutLocked() {
...
long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
}
持续时间的默认值为
private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds
其他回答
我已经开发了一个自定义吐司类,您可以显示吐司所需的持续时间(以毫秒计)
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public final class ToastHelper {
private static final String TAG = ToastHelper.class.getName();
public static interface OnShowListener {
public void onShow(ToastHelper toast);
}
public static interface OnDismissListener {
public void onDismiss(ToastHelper toast);
}
private static final int WIDTH_PADDING_IN_DIP = 25;
private static final int HEIGHT_PADDING_IN_DIP = 15;
private static final long DEFAULT_DURATION_MILLIS = 2000L;
private final Context context;
private final WindowManager windowManager;
private View toastView;
private int gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
private int mX;
private int mY;
private long duration = DEFAULT_DURATION_MILLIS;
private CharSequence text = "";
private int horizontalMargin;
private int verticalMargin;
private WindowManager.LayoutParams params;
private Handler handler;
private boolean isShowing;
private boolean leadingInfinite;
private OnShowListener onShowListener;
private OnDismissListener onDismissListener;
private final Runnable timer = new Runnable() {
@Override
public void run() {
cancel();
}
};
public ToastHelper(Context context) {
Context mContext = context.getApplicationContext();
if (mContext == null) {
mContext = context;
}
this.context = mContext;
windowManager = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
init();
}
private void init() {
mY = context.getResources().getDisplayMetrics().widthPixels / 5;
params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = android.graphics.PixelFormat.TRANSLUCENT;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("ToastHelper");
params.alpha = 1.0f;
// params.buttonBrightness = 1.0f;
params.packageName = context.getPackageName();
params.windowAnimations = android.R.style.Animation_Toast;
}
@SuppressWarnings("deprecation")
@android.annotation.TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private View getDefaultToastView() {
TextView textView = new TextView(context);
textView.setText(text);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
textView.setClickable(false);
textView.setFocusable(false);
textView.setFocusableInTouchMode(false);
textView.setTextColor(android.graphics.Color.WHITE);
// textView.setBackgroundColor(Color.BLACK);
android.graphics.drawable.Drawable drawable = context.getResources()
.getDrawable(android.R.drawable.toast_frame);
if (Build.VERSION.SDK_INT < 16) {
textView.setBackgroundDrawable(drawable);
} else {
textView.setBackground(drawable);
}
int wP = getPixFromDip(context, WIDTH_PADDING_IN_DIP);
int hP = getPixFromDip(context, HEIGHT_PADDING_IN_DIP);
textView.setPadding(wP, hP, wP, hP);
return textView;
}
private static int getPixFromDip(Context context, int dip) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dip, context.getResources().getDisplayMetrics());
}
public void cancel() {
removeView(true);
}
private void removeView(boolean invokeListener) {
if (toastView != null && toastView.getParent() != null) {
try {
Log.i(TAG, "Cancelling Toast...");
windowManager.removeView(toastView);
handler.removeCallbacks(timer);
} finally {
isShowing = false;
if (onDismissListener != null && invokeListener) {
onDismissListener.onDismiss(this);
}
}
}
}
public void show() {
if (leadingInfinite) {
throw new InfiniteLoopException(
"Calling show() in OnShowListener leads to infinite loop.");
}
cancel();
if (onShowListener != null) {
leadingInfinite = true;
onShowListener.onShow(this);
leadingInfinite = false;
}
if (toastView == null) {
toastView = getDefaultToastView();
}
params.gravity = android.support.v4.view.GravityCompat
.getAbsoluteGravity(gravity, android.support.v4.view.ViewCompat
.getLayoutDirection(toastView));
if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
params.horizontalWeight = 1.0f;
}
if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
params.verticalWeight = 1.0f;
}
params.x = mX;
params.y = mY;
params.verticalMargin = verticalMargin;
params.horizontalMargin = horizontalMargin;
removeView(false);
windowManager.addView(toastView, params);
isShowing = true;
if (handler == null) {
handler = new Handler();
}
handler.postDelayed(timer, duration);
}
public boolean isShowing() {
return isShowing;
}
public void setDuration(long durationMillis) {
this.duration = durationMillis;
}
public void setView(View view) {
removeView(false);
toastView = view;
}
public void setText(CharSequence text) {
this.text = text;
}
public void setText(int resId) {
text = context.getString(resId);
}
public void setGravity(int gravity, int xOffset, int yOffset) {
this.gravity = gravity;
mX = xOffset;
mY = yOffset;
}
public void setMargin(int horizontalMargin, int verticalMargin) {
this.horizontalMargin = horizontalMargin;
this.verticalMargin = verticalMargin;
}
public long getDuration() {
return duration;
}
public int getGravity() {
return gravity;
}
public int getHorizontalMargin() {
return horizontalMargin;
}
public int getVerticalMargin() {
return verticalMargin;
}
public int getXOffset() {
return mX;
}
public int getYOffset() {
return mY;
}
public View getView() {
return toastView;
}
public void setOnShowListener(OnShowListener onShowListener) {
this.onShowListener = onShowListener;
}
public void setOnDismissListener(OnDismissListener onDismissListener) {
this.onDismissListener = onDismissListener;
}
public static ToastHelper makeText(Context context, CharSequence text,
long durationMillis) {
ToastHelper helper = new ToastHelper(context);
helper.setText(text);
helper.setDuration(durationMillis);
return helper;
}
public static ToastHelper makeText(Context context, int resId,
long durationMillis) {
String string = context.getString(resId);
return makeText(context, string, durationMillis);
}
public static ToastHelper makeText(Context context, CharSequence text) {
return makeText(context, text, DEFAULT_DURATION_MILLIS);
}
public static ToastHelper makeText(Context context, int resId) {
return makeText(context, resId, DEFAULT_DURATION_MILLIS);
}
public static void showToast(Context context, CharSequence text) {
makeText(context, text, DEFAULT_DURATION_MILLIS).show();
}
public static void showToast(Context context, int resId) {
makeText(context, resId, DEFAULT_DURATION_MILLIS).show();
}
private static class InfiniteLoopException extends RuntimeException {
private static final long serialVersionUID = 6176352792639864360L;
private InfiniteLoopException(String msg) {
super(msg);
}
}
}
创建略长的消息的一个非常简单的方法如下:
private Toast myToast;
public MyView(Context context) {
myToast = Toast.makeText(getContext(), "", Toast.LENGTH_LONG);
}
private Runnable extendStatusMessageLengthRunnable = new Runnable() {
@Override
public void run() {
//Show the toast for another interval.
myToast.show();
}
};
public void displayMyToast(final String statusMessage, boolean extraLongDuration) {
removeCallbacks(extendStatusMessageLengthRunnable);
myToast.setText(statusMessage);
myToast.show();
if(extraLongDuration) {
postDelayed(extendStatusMessageLengthRunnable, 3000L);
}
}
注意,上面的示例消除了LENGTH_SHORT选项以保持示例简单。
通常不希望使用Toast消息在很长时间间隔内显示消息,因为这不是Toast类的预期目的。但是有时候,你需要显示的文本量可能需要用户超过3.5秒的时间来阅读,在这种情况下,稍微延长时间(例如,如上所示,到6.5秒)可能是有用的,并且与预期的用法一致。
吐司持续时间可以使用专门运行吐司的线程来破解。这是有效的(运行吐司10秒,修改睡眠和ctr到你的喜欢):
final Toast toast = Toast.makeText(this, "Your Message", Toast.LENGTH_LONG);
Thread t = new Thread(){
public void run(){
int ctr = 0;
try{
while( ctr<10 ){
toast.show();
sleep(1000);
ctr++;
}
} catch (Exception e) {
Log.e("Error", "", e);
}
}
};
t.start();
LONG_DELAY吐司显示为3.5秒,SHORT_DELAY吐司显示为2秒。
Toast内部使用INotificationManager并在每次调用Toast.show()时调用它的enqueueToast方法。
使用SHORT_DELAY调用show()两次将再次将同一toast排队。它将显示4秒(2秒+ 2秒)。
类似地,两次使用LONG_DELAY调用show()将再次将同一toast排队。它将显示7秒(3.5秒+ 3.5秒)
正如其他人提到的,Android toast可以是LENGTH_LONG或LENGTH_SHORT。这是没有办法的,你也不应该遵循发布的任何“技巧”。
toast的目的是显示“非必要的”信息,由于它们的持久影响,如果消息的持续时间超过一定的阈值,消息可能会脱离上下文。如果股票吐司被修改,使它们可以显示比LENGTH_LONG更长的时间,消息将在屏幕上停留,直到应用程序的进程终止,因为吐司视图被添加到WindowManager,而不是应用程序中的ViewGroup。我认为这就是硬编码的原因。
如果您确实需要显示toast样式的消息超过3.5秒,我建议构建一个附加到Activity内容的视图,这样当用户退出应用程序时,它就会消失。我的SuperToasts库处理这个问题和许多其他问题,请随意使用它!您很可能对使用SuperActivityToasts感兴趣
推荐文章
- 如何分配文本大小在sp值使用java代码
- Manifest合并失败:uses-sdk:minSdkVersion 14
- 为什么Android工作室说“等待调试器”如果我不调试?
- 如何检查我的EditText字段是否为空?
- Android从图库中选择图像
- 后台任务,进度对话框,方向改变-有任何100%工作的解决方案吗?
- Android:垂直对齐多行EditText(文本区域)
- Android无尽列表
- Android room persistent: AppDatabase_Impl不存在
- 错误:执行失败的任务':app:compileDebugKotlin'。>编译错误。详细信息请参见日志
- 在Android中使用URI生成器或使用变量创建URL
- 缩放图像以填充ImageView宽度并保持纵横比
- 列表视图的自定义适配器
- 在Android中设置TextView span的颜色
- 如何以编程方式在RelativeLayout中布局视图?