Android Toast 长期显示解决方案

Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,
Toast是没有焦点的,而且Toast显示的时间有限, 过一定的时间就会自动消失。
下面用一个实例来看看如何使用Toast。
首先建立一个ToastExample的项目,放置3个按钮,分别为 Text Only,Icon Only,Text and Icon。

Text Only
Toast.makeText(getApplicationContext(), "Text toast test!", Toast.LENGTH_LONG).show();

Icon Only
Toast toast = new Toast(getApplicationContext());
ImageView view = new ImageView(getApplicationContext());
view.setImageResource(R.drawable.ic_dialog_alert);
toast.setView(view);
toast.show();

Text and Icon
Toast toast = Toast.makeText(getApplicationContext(), "Text and Icon test!", Toast.LENGTH_LONG);
View textView = toast.getView();
LinearLayout lay = new LinearLayout(getApplicationContext());
lay.setOrientation(LinearLayout.HORIZONTAL);
ImageView view = new ImageView(getApplicationContext());
view.setImageResource(R.drawable.ic_dialog_alert);
lay.addView(view);
lay.addView(textView);
toast.setView(lay);
toast.show();


自己写了一个简化类,把Toast封装在里面,可以满足基本应用。

  public class MyToast {

  private static final String TAG = "MyToast";

  public static final int LENGTH_MAX = -1; //show until hide() function invoked

  boolean mCanceled = true;

  Handler mHandler;

  Context mContext;

  Toast mToast;

  public MyToast(Context context) {

  this(context,new Handler());

  }

  public MyToast(Context context,Handler h) {

  mContext = context;

  mHandler = h;

  mToast = Toast.makeText(mContext,"",Toast.LENGTH_SHORT);

  mToast.setGravity(Gravity.BOTTOM, 0, 0);

  }

  public void show(int resId,int duration) {

  mToast.setText(resId);

  if(duration != LENGTH_MAX) {

  mToast.setDuration(duration);

  mToast.show();

  } else if(mCanceled) {

  mToast.setDuration(Toast.LENGTH_LONG);

  mCanceled = false;

  showUntilCancel();

  }

  }

  public void show(String text,int duration) {

  mToast.setText(text);

  if(duration != LENGTH_MAX) {

  mToast.setDuration(duration);

  mToast.show();

  } else {

  if(mCanceled) {

  mToast.setDuration(Toast.LENGTH_LONG);

  mCanceled = false;

  showUntilCancel();

  }

  }

  }

  public void hide() {

  Log.d(TAG,"hide");

  mToast.cancel();

  mCanceled = true;

  }

  public boolean isShowing() {

  return !mCanceled;

  }

  private void showUntilCancel() {

  if(mCanceled)

  return;

  mToast.show();

  mHandler.postDelayed(new Runnable() {

  public void run() {

  showUntilCancel();

  }

  },3000);

  }

  }

更多相关文章

  1. Android监听键盘显示和隐藏
  2. Android之UI学习篇八:使用GridView实现九宫格的菜单
  3. android不让程序显示在最近程序列表中
  4. Android(安卓)实用工具Hierarchy Viewer实战
  5. Android(安卓)屏幕分辩率相关问题
  6. Android菜单详解
  7. android中scaleType详解
  8. Android修改系统时间(应用程序获得系统权限)
  9. Android屏幕相关设置

随机推荐

  1. Android RakNet 系列之三 移植Portaudio
  2. Android中的prelink技术
  3. android多国语言文件夹汇总
  4. android ui界面设计开发demo-智慧社区ui
  5. Maven开发Android指南
  6. 收藏Android学习相关资料
  7. Android:Camera
  8. Static interface methods are only supp
  9. Android手机屏幕的三种状态
  10. Android 画图之Matrix(二)