我有以下代码:
private Toast movieRecordToast; private void displayNextMovie() { if (movieRecordToast != null) movieRecordToast.cancel(); // cancel prevIoUs Toast (if user changes movies too often) movieRecordToast = Toast.makeText(getApplicationContext(),"Next",Toast.LENGTH_SHORT); movieRecordToast.show(); private void displayPrevMovie() { if (movieRecordToast != null) movieRecordToast.cancel(); movieRecordToast = Toast.makeText(getApplicationContext(),"Prev",Toast.LENGTH_SHORT); movieRecordToast.show();
但是如果displayNextMovie被快速调用几次,然后显示displayPrevMovie,“Next”Toast仍然显示,只有在显示“Prev”之后.
看起来取消不正常.
解决方法
每次您想要显示一个新的文本时,您可以轻松地只保留一个Toast对象,而不需要创建一个新的Toast对象,并取消当前的Toast.在显示下一个Toast之前,您可以使用Toast.setText()函数更改文本.
示例代码:
private Toast mToastText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create the object once. mToastText = Toast.makeText(this,"",Toast.LENGTH_SHORT); } private void displayText(final String message) { mToastText.cancel(); mToastText.setText(message); mToastText.show(); }