当为Toast使用setDuration()时,是否可以设置一个自定义长度或至少比Toast. length_long更长的长度?
当前回答
将吐司设置为以毫秒为单位的特定时间段:
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);
}
}
}
其他回答
LENGTH_SHORT和LENGTH_LONG的值分别为0和1。这意味着它们被视为标志,而不是实际的持续时间,所以我认为不可能将持续时间设置为这些值以外的任何东西。
如果想要长时间地向用户显示消息,可以考虑使用状态栏通知。当状态栏通知不再相关时,可以通过编程方式取消它们。
你可能想试试:
for (int i=0; i < 2; i++)
{
Toast.makeText(this, "blah", Toast.LENGTH_LONG).show();
}
使时间加倍。如果你指定3而不是2,它会使时间增加三倍等等。
这段文字将在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();
下面是我用上面的代码创建的一个自定义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();
}
}
简单地使用SuperToast在任何情况下都可以做出优雅的吐司。让你的吐司颜色鲜艳。编辑你的字体颜色和大小。希望这对你来说都是一体的。
推荐文章
- 如何解决INSTALL_FAILED_DEXOPT错误?
- 有没有办法自动安装Android SDK ?
- 如何检查一个视图在Android中是否可见?
- Android是否保留。apk文件?如果有,在哪里?
- 在Android 5棒棒糖中,通知栏图标变成白色
- 从URI获取真实路径,Android奇巧新的存储访问框架
- 如何检查JSON键是否存在?
- ImageView -有高度匹配宽度?
- 如何确定在android文件的MIME类型?
- 这是在Android中获取用户位置的好方法
- Android从左到右幻灯片动画
- 如何检索视图的维度?
- 如何改变菜单项的文本颜色在安卓?
- Android选择器和文本颜色
- 视图绑定-我如何获得包含布局的绑定?