Tuesday, December 15, 2009

Customize Toast Messages in Android

Since I've started developing for the Android platform, I've found Toast messages to be extremely useful. They are simple to instantiate, and look very sleek. Some instances though, wouldn't work with a Toast message because of the nature of their message. An error or notification doesn't seem adequate for a Toast message. Primarily because those types of messages need to grab the users attention, and most often use colors like red or yellow.

I wanted to use the Toast message for a notification, but wanted a yellow background instead. So, I wrapped the static toast method, makeText, with another static class that looks like this..

...


public static void show(Context ctx, String message, boolean notify) {

     Toast t = Toast.makeText(ctx, message, Toast.LENGTH_LONG);
     // if the message is a notify, modify the Toast view

     if (notify) {
            int offset = 100;

            // get the layout, center it, and change the background
            LinearLayout layout = (LinearLayout) t.getView();
            layout.setGravity(Gravity.CENTER);
            layout.setBackgroundResource(R.drawable.toast_frame_yellow);
            // get the text view, change the color, and make it narrower
            TextView tv = (TextView) layout.getChildAt(0);
            tv.setTextColor(Color.BLACK);
            tv.setGravity(Gravity.CENTER);
            tv.setMaxWidth(ctx.getResources().getDisplayMetrics().widthPixels - offset);
      }
                                                                     
      t.show();
                                                                      

                                                                        
}                                                                     

                                                                                                                                           

...


Most of this explains itself. The new background drawable that I used is the btn_default_pressed.9.png image, which is available in the Android source code. I chose this in order to save time. It's already a yellow/orange tone, and it's a 9-patch, so it'll stretch nicely. The maxWidth was changed in order to make the Toast view narrower...just a personal preference.

Here's the end result...


No comments:

Post a Comment