Android Java comments edit

Update: I was not originally checking to make sure there were any child views before getting the TextView. This has been fixed thanks to @stroughtonsmith.

I was recently working on an Android sample where I wanted to display a toast in the app.  By default, a toast will appear at the bottom of the screen with no special formatting consideration given to the text (i.e. it’s aligned to the left side).  This wasn’t really the experience I wanted the user to have.  What I wanted was for the text to be centered in the toast.  Then I decided I wanted the toast centered on the screen.  Thankfully these are all easy tasks to accomplish. 

The normal toast

Creating a toast is a very easy thing to accomplish.  Here’s the code I can use to show a toast from an Android Activity:

The first parameter is the context (i.e. the Activity), then followed by the text to display.  Lastly we have the length of time to display the toast (which we’re using the Toast.LENGTH_SHORT constant for).  Finally we call show() on the returned Toast object.  This results in a toast which looks like this:

Normal Toast

If there was a little less text, this might look fine as it would almost appear centered.  Unfortunately, unless we know the exact size of our toast text all the time, it’s pretty likely we’ll run into a situation (like this one) where it doesn’t look good.

Centering the text

Centering the text is pretty simple and requires us to pull out the TextView that is actually being used to display the text and then set it’s gravity like this:

Notice that we have to first pull out a LinearLayout because that is the view inside our Toast.  Next we can get the TextView as the first child of the LinearLayout.  Then we can call setGravity on our TextView.  When we do this, our toast looks like this:

toast center text

Centering the toast in the screen

Centering our toast in the screen is actually much easier than centering the text.  In fact we can do it with just one additional line of code (after we separate out the toast creation and showing):

We’ve just added a call to setGravity for our Toast (where as before we were setting the gravity on our TextView).  Now when we display the toast it will look like this:

Toast center screen

Putting it all together: centering the toast and text

If you want to center the text in the toast and the toast in the screen, you just need to put the last two things together:

We’ve just taken the “center text” example and dropped in the new line from the “center toast” example.  Now when we show our toast, it looks like this:

Centering a toast and it's text


Today we looked at how easy it is to adjust the position of a toast in Android as well as how to adjust the alignment of the text inside of that toast.  Using what we’ve demonstrated today, you should be able to figure out how to place your toasts wherever you might want to and in any alignment you need.

Chris Risner