我这个主要是缩短Toast显示时间,要延长时间的话,可自行更改
废话不多说哈,见代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
import android.content.Context; import android.os.CountDownTimer; import android.util.Log; import android.widget.Toast; public class ToastUtil { private String TAG = "ToastUtil" ; private Toast mToast; private TimeCount timeCount; private String message; private boolean canceled = true ; public ToastUtil(Context context, String msg) { message = msg; Log.i( "ToastUtil" , "Toast start..." ); if (mToast == null ) { mToast =Toast.makeText(context,message,Toast.LENGTH_SHORT); Log.i( "ToastUtil" , "Toast create..." ); } } /** * 自定义居中显示toast */ public void show() { mToast.show(); Log.i( "ToastUtil" , "Toast show..." ); } /** * 自定义时长、居中显示toast * @param duration */ public void show( int duration) { timeCount = new TimeCount(duration, 100 ); Log.i( "ToastUtil" , "Toast show..." ); if (canceled) { timeCount.start(); show(); canceled = false ; } } /** * 隐藏toast */ private void hide() { if (mToast != null ) { mToast.cancel(); } canceled = true ; Log.i( "ToastUtil" , "Toast that customed duration hide..." ); } /** * 自定义计时器 */ private class TimeCount extends CountDownTimer { public TimeCount( long millisInFuture, long countDownInterval) { super (millisInFuture, countDownInterval); //millisInFuture总计时长,countDownInterval时间间隔(一般为1000ms) } @Override public void onTick( long millisUntilFinished) { Log.e(TAG, ": " + millisUntilFinished / 100 + "后消失" ); } @Override public void onFinish() { hide(); //记数结束后调用取消Toast的显示 } } } |
使用方式:
1
2
3
4
|
ToastUtil toastUtil = new ToastUtil(MainActivity. this , "保存成功!" ); //MainActivity.this为 //Context, toastUtil.show( 500 ); |
总结
以上所述是小编给大家介绍的Android 自定义缩短Toast显示时间的实例代码,希望对大家有所帮助!
原文链接:https://blog.csdn.net/weixin_40008286/article/details/103817000