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.widget.TextView 属性详解
  2. android学习(1)——TextView属性
  3. Android(安卓)实用工具Hierarchy Viewer实战
  4. Android之UI设计TextView属性
  5. android图表收益曲线-MPAndroidChart
  6. Android之Adapter用法总结
  7. 【Android】19.3 ContentProvider及安卓进一步封装后的相关类
  8. android:layout_weight属性详解
  9. android:layout_weight属性详解

随机推荐

  1. Android(安卓)四种加载方式详解(standard
  2. android是什么意思
  3. Android中MVC的具体体现
  4. Android 的表格控件GridView学习
  5. android之ContentProvider和Uri详解
  6. Android学习路线(二十八)保存文件
  7. Android设备之间通过Wifi通信的示例代码
  8. Android App多个入口的实现方法
  9. 开发自己的监控系统三、移动篇(android)
  10. Android应用市场付费比例35% 天气应用最