Saturday 17 October 2015

Android: Alert using 'Toast' and 'Alert Dialogue'

   Alert has a wide number of uses in every app such as to show 'exit confirmation', 'do you want to continue', to show offers, etc... the endless uses of alert continues.. In android platform we have mainly to kinds of alert which are 'toast' and  alert using 'Builder'

Alert Dialogue 
   Its a bit advanced alert which popups and disappears after user action. You could have a title, message and buttons
in it.



   Consider the below code! Replace the MainActivity with your activity, "Confirm Exit..." with your title and "Are you sure to exit?" with your description. "YES" and "NO" are the texts to be shown on the buttons.

In the below code you could also call your methods which you want to trigger on pressing respective buttons.


Java:
 public void rYouSureToExit() {  
           Builder var6 = new Builder(MainActivity.this);  
           var6.setTitle("Confirm Exit...");  
           var6.setMessage("Are you sure to exit?");  
           var6.setPositiveButton("YES",  
                     new android.content.DialogInterface.OnClickListener() {  
                          public void onClick(DialogInterface var1, int var2) {  
                               finish();  
                          }  
                     });  
           var6.setNegativeButton("NO",  
                     new android.content.DialogInterface.OnClickListener() {  
                          public void onClick(DialogInterface var1, int var2) {  
                               var1.cancel();  
                          }  
                     });  
           var6.show();  
      }  

Toast
 Its a simple alert which popups and disappears after a fixed time. You could add a message body to it.


Java:
 Toast.makeText(getApplicationContext(),"This is a toast!", 1).show();  


No comments:

Post a Comment