简体   繁体   中英

Kill the Toast Message

In my App there are 13 buttons with different toasts. When i click the other button the toast is not stopping destroying properly , this is my code.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button one = (Button) this.findViewById(R.id.gg);
        final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.gg);
        one.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                Toast toast  = Toast.makeText(MainActivity.this, "Good Game", Toast.LENGTH_SHORT);
                toast.show();
                mp1.start();
                toast.cancel();
            }
        });

You can cancel individual Toasts by calling cancel() on the Toast object

 if (toast != null)
 {
   toast.cancel();
 } 

You may refer Kill android toast?

You need to add a duration to your toast, that is the way toast self-destruct.

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

You can find many many examples on toast implementation.

Android Developer Website - Toast Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM