Skip to main content

Alert Box (code)


Now lets discuss a small topic which may be used sometimes.
An Alert Box......................

Sometimes we may come across few alert boxes saying Do you want to continue with a single button or two or three buttons.

Alert box, as the name suggests it alerts and interrupts the user to perform short tasks that are related to the application.

When alert box is displayed the current task loses focus and the dialog accepts the whole focus.
This simply means that we can interact only with the alert box and not with the previous task.


Now lets get into the details how to display an alert dialog box in android.

An Alert box can be done either through java code or inflating an xml file
While we are inflating an xml file we can have any views other than buttons in the alert box. (This is a custom alert box).

  • 1.A simple way to create an alert dialog is to set the theme property for the activity which you want to display as a alert dialog.

          android:theme="@android:style/Theme.Dialog"


  • Now lets discuss how it can be done using java code.


Firstly do the following :

 1. AlertDialog.Builder builder = new AlertDialog.Builder(YourClassName.this);

       Here we are creating a Builder object for the current context. This will be used in the following                             steps.






If you observe we can see the following : 

  1. Title to the alert dialog box (ALERT)
  2. Message in the Alert dialog Box (this is a alert box.Click yes/no)
  3. And finally two buttons yes and no.
As i said the Builder object is used in the following steps, the title , message and the buttons are set using the builder object.

To set the title to the dialog box, we can use the following line line : 
                   builder.setTitle("ALERT");

To set a message to the alert dialog box, we use
                   builder.setMessage("this is an alert box. Click Yes/No");

And the 'yes' and 'no' buttons can be displayed and can be handled using the code :
  1. buillder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

  2. @Override
  3. public void onClick(DialogInterface dialog, int which) {

  4. Toast.makeText(DisplayAlert.this, "You clicked yes",
  5. Toast.LENGTH_SHORT).show();
  6. }
  7. });
  8.   

And the other button for 'no' can be dislayed and handled using a similar code as above.


  1. builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

  2. @Override
  3. public void onClick(DialogInterface dialog, int which) {

  4. Toast.makeText(DisplayAlert.this, "You clicked no",
  5. Toast.LENGTH_SHORT).show();
  6. dialog.dismiss();
  7. }
  8. });
In the similar way we can define a neutral button.


Finally we need to create and show the alert box which can be done using the following lines :
  1. AlertDialog alertdialog = builder.create();

  2. alertdialog.show();

Now let us see a sample example where i am having a button and the click of the button an alert dialog box appears.

Following is the xml file :
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:orientation="vertical" >

  6.     <Button
  7.         android:id="@+id/main_BTN_display"
  8.         android:layout_width="wrap_content"
  9.         android:layout_height="wrap_content"
  10.         android:text="DISPLAY" />

  11. </LinearLayout>
And following is the activity file :


  1. import android.app.Activity;
  2. import android.app.AlertDialog;
  3. import android.content.DialogInterface;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.Toast;

  9. /**
  10.  * 
  11.  * 
  12.  * Class that displays an alert dialog box and handles Yes/No buttons.
  13.  */
  14. public class DisplayAlert extends Activity implements OnClickListener {
  15. Button mBTN_display;

  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);
  20. mBTN_display = (Button) findViewById(R.id.main_BTN_display);
  21. mBTN_display.setOnClickListener(this);
  22. }

  23. @Override
  24. public void onClick(View arg0) {

  25. display_Alert();
  26. }

  27. /**
  28.  * This method displays an alert dialog box and handles Yes/No buttons
  29.  */
  30. private void display_Alert() {

  31. AlertDialog.Builder builder = new AlertDialog.Builder(DisplayAlert.this);
  32. builder.setTitle("ALERT");
  33. builder.setMessage("this is an alert box. Click Yes/No");


    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    builder.setView(input);

  34. builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

  35. @Override
  36. public void onClick(DialogInterface dialog, int which) {

  37. Toast.makeText(DisplayAlert.this, "You clicked yes",
  38. Toast.LENGTH_SHORT).show();
  39. }
  40. });
  41. builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

  42. @Override
  43. public void onClick(DialogInterface dialog, int which) {

  44. Toast.makeText(DisplayAlert.this, "You clicked no",
  45. Toast.LENGTH_SHORT).show();
  46. dialog.dismiss();
  47. }
  48. });

  49. AlertDialog alertdialog = builder.create();
  50. alertdialog.show();

  51. }
  52. }
The text in the box is used to place an edit text in the alert box. (simply a customized alert box).
There is no change in the manifest file.

Thus on running the application we can get a alert dialog on click of the button.


Any suggestions are welcomed.
Please comment if anyone has some or the other problem with this one.






















































Comments

Popular posts from this blog

Image Slide Show

Hi everyone. In this tutorial i am going to show you all the code which when run will display the images as a slideshow. Below is the attached screen shot :  For this i am considering the images from the Sdcard's images folder where i am having all the images. Next to display the images i am using View Flipper concept. I am adding ImageViews to the viewflipper so that the images can be displayed onto the screen. Now lets start  Design an xml layout as below (say main.xml) <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent" >     <ViewFlipper         android:id="@+id/main_flipper"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"  

Template literals

Template literals: ES6   introduced many cool things among which one is ‘ Template literals ’   This is a new way of representing strings.    Normally we use either “(double quotes) or ‘(single quote) to represent a string in  JavaScript .   For example:   var name=”literal”;   Or    var name=’literal’;   But from ES6 there is a new way of doing it. We can use `(back tick) symbol which is present left to key ‘1’ in keyboard.    Ie.,   var name = `literal`;   Well when we already have “(double quotes) or ‘(single quote), what extra does `(back tick) do?   Template literals  shines well when we have some concatenation of strings or when creating multi-line strings.   Look at below to understand the power of Template literals.   Let's  take an example where we need to form a string where you are forming a string based on a button clicked. For example - “You clicked on login button”.     Old way:   var 

Localization using .ttf files

In my previous post  here  i gave some information on how to use the concept of localization for the languages that are supported by Android. Now suppose if u want to display a language that is not supported by android.......? Then what might be solution? I will be discussing a small example for doing this now. Suppose if you want to display some text like this " हिंदी " or  " தமிழ் " or  some thing like the text   here  any other language that is  not supported by android we can use .ttf files so that we can print the font we are interested. To achieve this first we need to download few .ttf files. You can google for a file you need, download it and place this into the assets folder. In the picture i am having few other ttf files which i included, But for the time being only the DroidSansRegionalAAd.ttf is discussed by me which i used to display the words of few languages of India as in the following picture. Now we need to refer to the ttf file i