Monday 16 May 2011

Toast Customization

Hi all

As we know that customization is a great feature of android widgets. we can customize Text view ,Buttons and other view .Like all of these we can also customize "Toast".
Toast is a very tiny  but important tool of android.In our  application,we use this tool for providing instant information to user like "Battery Low" signal or "Location provider enable /disable " information.
But sometime  these toast doesn't match with our application theme for example In red theme, the toast always display in black.
I have customize the toast  not only for color or back ground  but orientation also. By default toast displays in center but we can also customize their orientation means center ,left ,right.

The idea behind customizing the toast is that when we write

Toast.makeText(this,"Text....",Toast.LENGTH_SHORT).show();

Then in directly we are setting the text on text view
So i have extracting the Text View from toast and performing customization over it.
My code is as follows 


protected void myToast( CharSequence text, int ToastPos )
    {
    Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
    View textView = toast.getView();
    switch ( ToastPos )
    {
    case TOAST_LEFT:
    toast.setGravity( android.view.Gravity.BOTTOM | android.view.Gravity.LEFT, 00, 0);
    break;
    case TOAST_CENTER:
    toast.setGravity( android.view.Gravity.BOTTOM | android.view.Gravity.CENTER, 00, 0);
    break;
    case TOAST_RIGHT:
    toast.setGravity( android.view.Gravity.BOTTOM | android.view.Gravity.RIGHT, 00, 0);
    break;
    }
    textView.setBackgroundResource(R.drawable.icon);
    toast.show();
    }

Where TOAST_LEFT_POS,TOAST_CENTER_POS,TOAST_RIGHT_POS are three Constant
    private final int TOAST_LEFT=3;//android.view.Gravity.LEFT;
    private final int TOAST_CENTER=17;//android.view.Gravity.CENTER;
    private final int TOAST_RIGHT_POS=5;//android.view.Gravity.RIGHT;

so now instead of calling  
Toast.makeText(this,"",),show();
we need to call  
myToast("",orientation);

You can do some more customization over it like text size ,text style background and other.
I hope this tutorial is helpful for you.















1 comment: