先说明一下,本次需要用到Handle机制,因此不了解或者不熟悉Handle的同学,请先去看看Android上的Handle机制!
下面开始讲解代码实现详情!
先写一个包装类,就叫MyToast吧,如下
代码如下:
public class MyToast {
private Context mContext = null;
private Toast mToast = null;
private Handler mHandler = null;
private Runnable mToastThread = new Runnable() {
@Override
public void run() {
mToast.show();
mHandler.postDelayed(mToastThread, 3000);//每隔3秒显示一次,经测试,这个时间间隔效果是最好
}
};
public MyToast(Context context){
mContext = context;
mHandler = new Handler(mContext.getMainLooper());
mToast = Toast.makeText(mContext, "自由@飞翔", Toast.LENGTH_LONG);
}
public void setText(String text){
mToast.setText(text);
}
public void show(){
mHandler.post(mToastThread);
}
public void cancel() {
mHandler.removeCallbacks(mToastThread);//先把显示线程删除
mToast.cancel();// 把最后一个线程的显示效果cancel掉,就一了百了了
}
}
MainActivity 的代码如下:
代码如下:
public class MainActivity extends Activity implements OnClickListener{
private Button show_button;
private Button cancel_button;
private MyToast myToast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
show_button = (Button) findViewById(R.id.show_button);
cancel_button = (Button) findViewById(R.id.cancel_button);
show_button.setOnClickListener(this);
cancel_button.setOnClickListener(this);
myToast = new MyToast(this);
}
@Override
public void onClick(View v) {
if(v == show_button){
myToast.show();
}else if (v == cancel_button) {
myToast.cancel();
}
}
}