将setDuration()用于Toast时,是否可以设置自定义长度或至少长于Toast.LENGTH_LONG
?
toast
标签来。我认为标签在那里可以帮助搜索和排序,toast
并且绝对是常见的搜索。android
和toast
自己看起来很完美。
将setDuration()用于Toast时,是否可以设置自定义长度或至少长于Toast.LENGTH_LONG
?
toast
标签来。我认为标签在那里可以帮助搜索和排序,toast
并且绝对是常见的搜索。android
和toast
自己看起来很完美。
Answers:
的价值观LENGTH_SHORT
和LENGTH_LONG
是0和1,这意味着它们将被视为标志,而不是实际的持续时间,所以我不认为这将有可能设置持续时间比这些数值的任何其他。
如果您想向用户显示消息的时间更长,请考虑“ 状态栏通知”。当状态栏通知不再相关时,可以通过编程方式取消它们。
如果您深入研究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
您可能要尝试:
for (int i=0; i < 2; i++)
{
Toast.makeText(this, "blah", Toast.LENGTH_LONG).show();
}
加倍时间。如果您指定3而不是2,它将使时间增加三倍。
Toast.cancel()
在适当的地方使用
如果您希望a Toast
持续存在,我发现您可以通过反复打个Timer
电话来解决问题(大约toast.show()
每秒应这样做)。show()
如果Toast
已经显示,则调用不会中断任何操作,但会刷新屏幕上停留的时间。
ViewGroup
OnTouch
事件中使用布尔标志之类的东西处理起来非常简单。要对此进行优化,您可能应该使计时器重复接近Toast
屏幕上显示的实际时间(长3.5秒,短2秒)
我开发了一个Custom Toast类,您可以通过该类向Toast显示所需的持续时间(以毫秒为单位)
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);
}
}
}
我已经为此编写了一个辅助类。您可以在github上查看代码:https : //github.com/quiqueqs/Toast-Expander/blob/master/src/com/thirtymatches/toasted/ToastedActivity.java
这是显示烤面包5秒钟(或5000毫秒)的方式:
Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);
我知道我来晚了,但是我接受了Regis_AG的回答,并将其包装在帮助程序类中,效果很好。
public class Toaster {
private static final int SHORT_TOAST_DURATION = 2000;
private Toaster() {}
public static void makeLongToast(String text, long durationInMillis) {
final Toast t = Toast.makeText(App.context(), text, Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
new CountDownTimer(Math.max(durationInMillis - SHORT_TOAST_DURATION, 1000), 1000) {
@Override
public void onFinish() {
t.show();
}
@Override
public void onTick(long millisUntilFinished) {
t.show();
}
}.start();
}
}
在您的应用程序代码中,只需执行以下操作:
Toaster.makeLongToast("Toasty!", 8000);
我知道答案很晚。我遇到了同样的问题,在研究了Android的toast源代码后,决定实现自己的裸露骨头Toast版本。
基本上,您需要创建一个新的窗口管理器,并使用处理程序显示和隐藏所需持续时间的窗口。
//Create your handler
Handler mHandler = new Handler();
//Custom Toast Layout
mLayout = layoutInflater.inflate(R.layout.customtoast, null);
//Initialisation
mWindowManager = (WindowManager) context.getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.gravity = Gravity.BOTTOM
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 = PixelFormat.TRANSLUCENT;
params.windowAnimations = android.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
布局初始化后,您可以使用自己的hide和show方法
public void handleShow() {
mWindowManager.addView(mLayout, mParams);
}
public void handleHide() {
if (mLayout != null) {
if (mLayout.getParent() != null) {
mWindowManager.removeView(mLayout);
}
mLayout = null;
}
现在,您所需要做的就是添加两个可运行线程,这些线程分别调用handleShow()和handleHide(),您可以将其发布到Handler。
Runnable toastShowRunnable = new Runnable() {
public void run() {
handleShow();
}
};
Runnable toastHideRunnable = new Runnable() {
public void run() {
handleHide();
}
};
最后一部分
public void show() {
mHandler.post(toastShowRunnable);
//The duration that you want
mHandler.postDelayed(toastHideRunnable, mDuration);
}
这是一个快速而肮脏的实现。.没有考虑任何性能。
LONG_DELAY吐司显示持续3.5秒,SHORT_DELAY吐司显示持续2秒。
Toast在内部使用INotificationManager并在每次调用Toast.show()时都调用它的enqueueToast方法。
两次用SHORT_DELAY调用show()将再次使相同的吐司入队。它将显示4秒钟(2秒钟+ 2秒钟)。
同样,用LONG_DELAY调用show()两次将再次使相同的吐司入队。它将显示7秒(3.5秒+ 3.5秒)
这是我使用上面的代码制作的自定义Toast类:
import android.content.Context;
import android.os.CountDownTimer;
import android.widget.Toast;
public class CustomToast extends Toast {
int mDuration;
boolean mShowing = false;
public CustomToast(Context context) {
super(context);
mDuration = 2;
}
/**
* Set the time to show the toast for (in seconds)
* @param seconds Seconds to display the toast
*/
@Override
public void setDuration(int seconds) {
super.setDuration(LENGTH_SHORT);
if(seconds < 2) seconds = 2; //Minimum
mDuration = seconds;
}
/**
* Show the toast for the given time
*/
@Override
public void show() {
super.show();
if(mShowing) return;
mShowing = true;
final Toast thisToast = this;
new CountDownTimer((mDuration-2)*1000, 1000)
{
public void onTick(long millisUntilFinished) {thisToast.show();}
public void onFinish() {thisToast.show(); mShowing = false;}
}.start();
}
}
如果您需要很长的Toast,有一个实用的选择,但是它要求您的用户单击OK(确定)按钮才能消失。您可以这样使用AlertDialog:
String message = "This is your message";
new AlertDialog.Builder(YourActivityName.this)
.setTitle("Optional Title (you can omit this)")
.setMessage(message)
.setPositiveButton("ok", null)
.show();
如果您有一条长消息,很可能是,您不知道用户阅读该消息要花费多长时间,因此有时最好要求用户单击“确定”按钮以继续。就我而言,当用户单击帮助图标时,我会使用这种技术。
Service
没有UI的类似的东西中实现。
正如其他人提到的,Android Toasts可以是LENGTH_LONG或LENGTH_SHORT。无法解决此问题,也不应遵循任何发布的“ hacks”。
Toast的目的是显示“非必要”信息,由于其挥之不去的影响,如果消息的持续时间超过某个阈值,则消息可能会脱离上下文。如果修改了股票Toast,以使它们可以显示的长度超过LENGTH_LONG,则该消息会在屏幕上徘徊,直到应用程序的进程终止,因为Toast视图被添加到WindowManager中而不是应用程序中的ViewGroup中。我认为这就是为什么要对其进行硬编码。
如果您绝对需要显示超过三分半秒的吐司风格消息,我建议您构建一个附加到活动内容的视图,这样,当用户退出应用程序时,该视图将消失。我的SuperToasts库处理了此问题以及许多其他问题,请随时使用!您很可能会对使用SuperActivityToasts感兴趣
只需在任何情况下使用SuperToast即可制作出优雅的吐司。使您的烤面包多彩。编辑您的字体颜色及其大小。希望这对您来说是合而为一的。
当您可以吃完整个小吃店时,为什么要吃吐司: https //developer.android.com/reference/android/support/design/widget/Snackbar.html
小吃吧>吐司,定制吐司,面包块
用户无法自定义吐司的持续时间。因为NotificationManagerService的scheduleTimeoutLocked()函数不使用字段持续时间。源代码如下。
private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
{
Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
mHandler.removeCallbacksAndMessages(r);
mHandler.sendMessageDelayed(m, delay);
}
使用Crouton,它是一个非常灵活的Toast库。
您可以像烤面包一样使用它:
Crouton.makeText(context, "YOUR_MESSAGE", Style.INFO);
或者甚至可以更深入地进行自定义,例如将时间设置为无限!例如,在这里我想显示一条祝酒消息,直到用户单击它为止。
private static void showMessage(final Activity context, MessageType type, String header, String message) {
View v = context.getLayoutInflater().inflate(R.layout.toast_layout, null);
TextView headerTv = (TextView) v.findViewById(R.id.toastHeader);
headerTv.setText(header);
TextView messageTv = (TextView) v.findViewById(R.id.toastMessage);
messageTv.setText(message);
ImageView toastIcon = (ImageView) v.findViewById(R.id.toastIcon);
final Crouton crouton = getCrouton(context, v);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Crouton.hide(crouton);
}
});
crouton.show();
}
private static Crouton getCrouton(final Activity context, View v) {
Crouton crouton = Crouton.make(context, v);
crouton.setConfiguration(new Configuration.Builder().setDuration(Configuration.DURATION_INFINITE).build());
return crouton;
}
将为吐司充气的客户布局。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:background="@drawable/shadow_container"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="@dimen/default_margin"
tools:ignore="Overdraw">
<ImageView
android:id="@+id/toastIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/default_spacing_full"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/toastHeader"
style="@style/ItemText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/toastMessage"
style="@style/ItemSubText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
可以使用专门运行烤面包的线程来破解烤面包的持续时间。可行(运行吐司10秒钟,根据自己的喜好修改睡眠和点击率):
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();
带有自定义背景和视图的烤面包对我来说很成功。我在nexus 7平板电脑中对其进行了测试,发现在循环过程中没有淡入淡出动画。继承人的实现:
public static void customToast(Context context, String message, int duration) {
for (int i = 0; i < duration; i++) {
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_layout, null);
TextView textViewToast = (TextView) view
.findViewById(R.id.textViewToast);
textViewToast.setText(message);
toast.setView(view);
toast.show();
}
}
这是上述代码中使用的自定义textview:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/fragment_background"
android:padding="8dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/blue" />
@ drawable / fragment_background使我的吐司像kitkat版本中那样圆角。您也可以在文件中添加其他视图。我计划在实时应用中实施此改进,以鼓励大家进行改进和评论。
此文字将在5秒钟内消失。
final Toast toast = Toast.makeText(getApplicationContext(), "My Text", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 5000); // Change to what you want
编辑:正如Itai Spector在评论中所说,它将显示约3.5秒,因此请使用以下代码:
int toastDuration = 5000; // in MilliSeconds
Toast mToast = Toast.makeText(this, "My text", Toast.LENGTH_LONG);
CountDownTimer countDownTimer;
countDownTimer = new CountDownTimer(toastDuration, 1000) {
public void onTick(long millisUntilFinished) {
mToast.show();
}
public void onFinish() {
mToast.cancel();
}
};
mToast.show();
countDownTimer.start();
不,并且这里列出的大多数/所有hacks在android 9中不再起作用。但是有一个更好的解决方案:如果您的消息需要保留,请使用对话框。
(new AlertDialog.Builder(this)).setTitle("Sorry!")
.setMessage("Please let me know by posting a beta comment on the play store .")
.setPositiveButton("OK", null).create().show();
创建稍长的消息的一种非常简单的方法如下:
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秒,在这种情况下,IMO稍微延长时间(例如,如上所示,为6.5秒)可能会有用并与预期用途一致。
将烤面包设置为特定的时间(以毫秒为单位):
public void toast(int millisec, String msg) {
Handler handler = null;
final Toast[] toasts = new Toast[1];
for(int i = 0; i < millisec; i+=2000) {
toasts[0] = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toasts[0].show();
if(handler == null) {
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toasts[0].cancel();
}
}, millisec);
}
}
}
private Toast mToastToShow;
public void showToast(View view) {
// Set the toast and duration
int toastDurationInMilliSeconds = 10000;
mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);
// Set the countdown to display the toast
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
// Show the toast and starts the countdown
mToastToShow.show();
toastCountDown.start();
}
在所有可用解决方案都失败之后,我终于有了使用递归的解决方法。
码:
//Recursive function, pass duration in seconds
public void showToast(int duration) {
if (duration <= 0)
return;
Toast.makeText(this, "Hello, it's a toast", Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
showToast(duration-1);
}
}, 1000);
}
Toast.makeText(this, "Text", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Text", Toast.LENGTH_LONG).show();
这个问题的非常简单的解决方案。他们的两倍或三倍将使吐司持续时间更长。这是唯一的解决方法。
您可以通过以下方法设置所需的时间(以毫秒为单位)Toast.makeText();
:
//40 seconds
long mToastLength = 40*1000
//this toast will be displayed for 40 seconds.
Toast.makeText(this, "Hello!!!!!", mToastLength).show();
toast
标签的任何理由?它看起来相关的问题..