有没有办法可以通过编程方式停止Toast消息?
假设我有一个按钮,我点击滚动查看Toast消息,在onclick事件中我想停止所有队列并只显示新的,我该怎么做?
我的代码的简化版本如下 - 代码:
public class Help extends Activity{
LinearLayout background;
int screenNo = 1;
Toast toast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
background = (LinearLayout) findViewById(R.id.helpLayout);
ImageButton next = (ImageButton) findViewById(R.id.imageButtonNext);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
toast.cancel();
showNextScreen();
}});
}
private void showMessageBox(String title, String msg) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(title);
b.setMessage(msg);
b.setPositiveButton("Next", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
showNextScreen();
}});
b.setNegativeButton("Quit Help", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
returnHome();
}});
b.show();
}
private void showNextScreen() {
int time = 7000;
String tstMsg = "error";
switch (screenNo) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
toast.cancel();
returnHome();
break;
default:
break;
}
if(screenNo < 5)
{
toast=Toast.makeText(this, tstMsg, time);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
screenNo++;
}
}
}
答案 0 :(得分:5)
这就是我实现这一目标的方式。
public static Toast toastShow;
public void showToast(Activity actRef, String message) {
if (toastShow == null
|| toastShow.getView().getWindowVisibility() != View.VISIBLE) {
toastShow = Toast.makeText(actRef, message, Toast.LENGTH_SHORT);
toastShow.setGravity(Gravity.CENTER, 0, 0);
toastShow.show();
}
}
在单独的类中定义上面的代码并实例化你想要显示消息的那个类,你就完成了它。
答案 1 :(得分:4)
创建自定义全局对象
private Toast toast;
在onCreate中初始化
toast = Toast.makeText(YOUR_CLASS_NAME.this, "", Toast.LENGTH_SHORT);
每当你需要展示Toast
时toast.setText("Hi....");
toast.show();
根据onPause或onDestroy
的要求杀死所有消息toast.cancel();
答案 2 :(得分:2)
你们cancel the Toast
object都是自由的。