~~~~我的生活,我的点点滴滴!!
Toast是Android中用来显示信息的一种机制,和Dialog不同,Toast没有焦点,而且Toast显示的时间有限,一定时间后就会自动消失。Toast一般用来提示用户的误操作。但是如果同时显示多个Toast信息时,系统会将这些Toast信息放到队列中,等前一个Toast信息显示关闭后才会显示下一个Toast信息。当用户在某些情况下,误操作多次时,使用 Toast提示会出现很多个Toast依次显示,在页面上停留很长时间,用户体验很不好!为了解决这一问题,每次创建Toast时先做一下判断,如果前面有Toast在显示,只需调用Toast中的setText()方法将要显示的信息替换即可。
自定义CustomToast代码如下:
public class CustomToast { private static Toast m_toast; private static Handler m_handler = new Handler(); private static Runnable m_runnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub m_toast.cancel(); } }; public static void showToast(Context context, String text, int duration) { m_handler.removeCallbacks(m_runnable); if( m_toast != null ) { m_toast.setText(text); } else { m_toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); } m_handler.postDelayed(m_runnable, duration); m_toast.show(); } public static void showToast(Context context, int resId, int duration) { showToast(context, context.getResources().getString(resId), duration); } };<span style="font-family:SimSun;font-size:14px;"> </span>
public static void showToast(Context mContext, int resId, int duration) { showToast(mContext, mContext.getResources().getString(resId), duration); }
public class MainActivity extends Activity { private int minP = 5; private int maxP = 100; private NumberPicker numpicker1 = null; private NumberPicker numpicker2 = null; final private CustomToast m_toast = new CustomToast(); private void showSelectedPrice() { m_toast.showToast(this, "您选择最低价格为:" + minP + ", 最高价格为:" + maxP, 1000); //Toast.makeText(this, , Toast.LENGTH_SHORT).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); numpicker1 = (NumberPicker)findViewById(R.id.numberPicker1); numpicker1.setMaxValue(maxP); numpicker1.setMinValue(minP); numpicker1.setValue(minP+10); numpicker1.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { // TODO Auto-generated method stub minP = newVal; showSelectedPrice(); } }); numpicker2 = (NumberPicker)findViewById(R.id.numberPicker2); numpicker2.setMaxValue(maxP); numpicker2.setMinValue(minP); numpicker2.setValue(minP+20); numpicker2.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { // TODO Auto-generated method stub maxP = newVal; showSelectedPrice(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }