Saturday 11 April 2015

Custom Toast in Android.

Customizing Toasts

The standard Toast message window is often sufficient, but in many situations you’ll want to cus- tomize its appearance and screen position. 
You can modify a Toast by setting its display position and assigning it alternative Views or layouts.

Let’s Make a Toast
It shows how to align a Toast to the bottom of the screen using the setGravity method. 

Aligning Toast text
 
Context context = this; 
String msg = “To the bride and groom!”; 
int duration = Toast.LENGTH_SHORT; 
Toast toast = Toast.makeText(context, msg, duration); 
int offsetX = 0; 
int offsetY = 0;
 
toast.setGravity(Gravity.BOTTOM, offsetX, offsetY); 
toast.show();

When a text message just isn’t going to get the job done, you can specify a custom View or layout to use a more complex, or more visual, display. 
Using setView on a Toast object, you can specify any View (including a layout) to display using the Toast mechanism. 

For example, assigns a layout, containing the CompassView Widget  along with a TextView, to be dis- played as a Toast.

Using Views to customize a Toast
 
Context context = getApplicationContext(); 
String msg = “Cheers!”;
int duration = Toast.LENGTH_LONG; 

Toast toast = Toast.makeText(context, msg, duration); 
toast.setGravity(Gravity.TOP, 0, 0);
 
LinearLayout ll = new LinearLayout(context); 
ll.setOrientation(LinearLayout.VERTICAL);
 
TextView myTextView = new TextView(context); 
CompassView cv = new CompassView(context);
myTextView.setText(msg);
 
int lHeight = LinearLayout.LayoutParams.FILL_PARENT; 
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
 
ll.addView(cv, new LinearLayout.LayoutParams(lHeight, lWidth)); 
ll.addView(myTextView, new LinearLayout.LayoutParams(lHeight, lWidth));
ll.setPadding(40, 50, 0, 50);
 
toast.setView(ll); 
toast.show();

The resulting Toast will appear.

Using Toasts in Worker Threads
 
As GUI components, Toasts must be created and shown on the GUI thread; otherwise, you risk throwing a cross-thread exception.A Handler is used to ensure that the Toast is opened on the GUI thread. 

Opening a Toast on the GUI thread
 
Handler handler = new Handler();
private void mainProcessing() 
{  
Thread thread = new Thread(null, doBackgroundThreadProcessing,                            ”Background”);  
thread.start(); }
 
private Runnable doBackgroundThreadProcessing = new Runnable() 
{  
public void run() 
{    
backgroundThreadProcessing();  
};

private void backgroundThreadProcessing() 
{  
handler.post(doUpdateGUI); }
 
// Runnable that executes the update GUI method. 
private Runnable doUpdateGUI = new Runnable() 
{  
public void run() 
{    
Context context = getApplicationContext();    
String msg = “To open mobile development!”;    
int duration = Toast.LENGTH_SHORT;    
Toast.makeText(context, msg, duration).show();  
};

No comments:

Post a Comment