65.9K
CodeProject is changing. Read more.
Home

Show a Toast in the Middle of the Android Screen

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (5 votes)

May 17, 2014

CPOL
viewsIcon

18632

Simple tip on how to show a toast in response to an event, and center it in the screen

Is the Handler Being Handled?

Sometimes, when you're adding event handlers for things such as button clicks/taps, you aren't going to add the actual code just yet, but you do want to receive a visual verification that the event handler code has been properly hooked up. You can always use LogCat while debugging, but especially when showing the project "as-is" (perhaps in "mockup" state), you might want to just show a simple message that basically says, "Yeah, I know, you clicked me."

I don't know about you, but I'm a little OCD-ish when it comes to having things centered (I still wonder why Windows forms aren't automatically set to display in the middle of the screen - it's a big pet peeve of mine). Anyway, enough of that; here's the code to show a "toast", centered in the middle of the emulator or device, in response to a button's "click" event:

    Button btn = (Button) findViewById(R.id.buttonNose);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO: Finish
            Toast tostada = Toast.makeText(MainActivity.this, 
            "You mashed the button, dude (or dudette)!", Toast.LENGTH_SHORT);
            tostada.setGravity(Gravity.CENTER, 0, 0);
            tostada.show();
        }
    });

Run the app, mash the button, and you will see it:

This is obviously a simple little snippet, but it can come in handy on occasion.