用过Android 中Toast的童鞋们都知道,Toast只能设置两种时间,即Toast.LENGTH_SHORT和Toast.LENGTH_LONG。而很多情况下这两种固定长度的时间并不能很好满足应用需求,所以我们必须自己控制时间。
聪明的程序猿们还是想出了不少办法,尽管Android在toast对象偷偷放入了队列(在调用show()的时候),我们可以通过handle和timer结合的机制来控制,比如下面代码段:
- handler = new Handler(){
- public void handleMessage(Message message)
- {
- switch (message.what)
- {
- case 1:
- try
- {
- Object obj = message.obj;
- Method method = obj.getClass().getDeclaredMethod("hide", null);
- method.invoke(obj, null);
- }
- catch (Exception e)
- {
- }
- }
- }
- };
- Timer toastTimer = new Timer(true);
- TimerTask toastTT = new TimerTask() {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- Message message = new Message();
- message.what = 1;
- Toast tt = Toast.makeText(m_App.getActivity(), "test", Toast.LENGTH_SHORT);
- tt.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 50);
- Field field = null;
- field.setAccessible(true);
- try {
- field = tt.getClass().getDeclaredField("mTN");
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Object obj = null;
- try {
- obj = field.get(tt);
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- message.obj = obj;
- handler.sendMessage(message);
- }
- };
- toastTimer.schedule(toastTT, 800);
- toastTimer.purge();
大致思路是这样,但是很可惜,Method method = obj.getClass().getDeclaredMethod("hide", null); 这种方法在4.0中已经不适用了。所以在4.0中我们利用这种思路,可以采用更为简单的办法。
- //首先定义全局变量mToast已经显示和隐藏函数
- private Toast mToast;
- public void showToast(String text) {
- if(mToast == null) {
- mToast = Toast.makeText(m_App.getActivity(), text, Toast.LENGTH_SHORT);
- } else {
- mToast.setText(text);
- mToast.setDuration(Toast.LENGTH_SHORT);
- }
- mToast.show();
- }
- public void cancelToast() {
- if (mToast != null) {
- mToast.cancel();
- }
- }
- //然后调用显示函数并向handler发消息
- showToast(“test toast”);
- Message delayMsg = m_Handler.obtainMessage(AIRPLAY_MESSAGE_HIDE_TOAST);
- m_Handler.sendMessageDelayed(delayMsg, AIRPLAY_TOAST_DISPLAY_TIME);
其中的AIRPLAY_TOAST_DISPLAY_TIME 就是我们想要Toast显示的时间长度了!
- //最后在handler中处理消息
- private Handler m_Handler = new Handler()
- {
- @Override
- public void handleMessage(Message msg) {
- // TODO Auto-generated method stub
- switch(msg.what)
- {
- case 0:
- break;
- case AIRPLAY_MESSAGE_HIDE_TOAST :
- {
- cancelToast();
- break;
- }