Android Tips, Techniques and Theory

PART 2: Creating Content with Java with Android Studio (Programming required)

With Simple Recipes

Go Back To TOC

Dialog

When your app needs to handle a small amount of user interaction WITHOUT having to open a new activity, you can use a dialog box. A dialog typically has a title, a message and one or more buttons (e.g., Submit / Cancel).

An activity can create multiple dialog boxes. Dialog Box methods include:

Notice that there is no Dialog component in the Palette panel. That’s because you don’t want a user to “see” a dialog when an activity (page) is shown initially.  The dialog is created and populated “on-the-fly” as an object.

Simple Dialog

Most dialogs are simple ones that have a title, message and one or more buttons.

EXAMPLE: DIALOG

We will create a simple dialog that has a title, a message and two buttons.

  1. Create a new project base off of the Empty Template and name it Simple Dialog App.
  2. Drag-and-drop a button to the bottom of the screen and give it an id of showDialogID.
  3. In the strings.xml file, create the following string resources for the title, message, etc.

    <string name=”dialogButtonLabel”>Show Dialog</string>
    <string name=”dialogTitle”>Confirmation Dialog</string>
    <string name=”dialogMessage”>Do you want to delete this file?</string>
    <string name=”positiveButton”>Yes</string>
    <string name=”negativeButton”>No</string>
    <string name="response">You click on the \'%s\' button.</string>

    NOTE: Notice the single quotes has been escaped by using back slashes (e.g., \'%s\').
  4. In Design view, select the button component and in the Properties panel, assign the dialogButtonLabel string resource for the text property.
  5. Add the following highlighted code to the MainActivity.java file:

    public class MainActivity extends AppCompatActivity {

    private Button showDialogButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    showDialogButton = (Button) findViewById(R.id.showDialog);
    showDialogButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    showDeleteDialog();
    }
    });
    }
    }

  6. Click inside of the showDeleteDialog(); statement and then press ALT+ENTER. In the drop down that appears select Create method ‘showDeleteDialog()’ and then in the Choose Target Class list, select MainActivity….

    NOTE: This will create the code stub for the showDeleteDialog() method.

  7. Write the following highlighted code in the showDeleteDialog() method:

    private void showDeleteDialog() {
    // Create Dialog Builder
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.dialogTitle);
    builder.setMessage(R.string.dialogMessage);
    // Set Positive button
    builder.setPositiveButton(R.string.positiveButton, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(MainActivity.this, getString(R.string.response,getString(R.string.positiveButton)), Toast.LENGTH_SHORT).show();
    }
    });
    // SetNegative button
    builder.setNegativeButton(R.string.negativeButton, new DialogInterface.OnClickListener() {
    @Override
    /* Unlike the onClick for the View interface that required (View, v), the dialog onClick interface re
    require two new arguments (DialogInterface and a integer value of which item is selected) */
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(MainActivity.this, getString(R.string.response,getString(R.string.negativeButton)), Toast.LENGTH_SHORT).show();
    }
    });
    // Create and show dialog
    AlertDialog dialog = builder.create();
    dialog.show();
    }


  8. CHECK POINT: Run the app in an emulator. You should see when you click on the Show Dialog button it will display a dialog with a title, message and Yes/No buttons. If you click on either the Yes or No button, it will show a Toast of what button was clicked on.

With a normal dialog, if a user click outside of the dialog bounding area or click the back button, the dialog will disappear. However, there are times when you will want a user to choose an option BEFORE he or she can advance further. This is where you will want to create a modal dialog box.

EXAMPLE: MODAL DIALOG

  1. Add the following highlighted code to set the setCancelable property to false BEFORE the create and show code:

    builder.setCancelable(false);
    // Create and show dialog
    AlertDialog dialog = builder.create();
    dialog.show();

  2. CHECK POINT: Run the app in an emulator. You should see this time that when you try to click OUTSIDE of the dialog box bounding area or click on the back button, the dialog is not dismissed as before.

EXAMPLE: Create Dialog box

  1. Create a new project using the Basic Activity Template and name it DialogBox App.
  2. In the MainActivity.java class file, add the following highlighted code to the onOptionsItemSelected() method:

    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("This is my dialog box")
    .setTitle("My Dialog Box")
    .create()
    .show();
            return true;
    }

    return super.onOptionsItemSelected(item);
    }

    CODE EXPLANATION:
    - A class named AlertDialog.Builder is created and instantiate with its constructor method and passed the current activity (this).
    - It is then CHAINED together using the following method:
    - .setMessage(“This is my dialog box”)
    .setTitle(“My Dialog Box”)
    .create()
    .show();

    NOTE: It is important to note that the methods are CHAINED TOGETHER so the semicolon is ony on the LAST method.

  3. CHECK POINT: Run the app in an emulator. You should see that if you click on the menu and select Settings the dialog box should display.

List Dialog

A list dialog is as the name implies a dialog that shows a list of options as oppose to a message and some buttons as in a regular dialog.

EXAMPLE: LIST DIALOG (REPLACE LATER WITH A DIALOGFRAMENT)
REPLACEMENT FOR showDialog()? http://developer.android.com/reference/android/app/Activity.html/
(the showDialog method from Activity is deprecated. Invoking a dialog elsewhere in code is not advisable since you will have to manage the the dialog yourself (e.g. orientation change). Not using the showDialog will result in occasional exceptions, the dialog is not linked to any Activity.)

We will create a simple list dialog that will display a list of Adobe apps and will display a Toast when a selection is made.

  1. Create a new project base off of the Empty Template and name it List Dialog App.
  2. Drag-and-drop a Button component to the bottom of the screen and give it an id of showListDialogButtonID.
  3. In the strings.xml file, create the following string resources for the button label, title, etc.

    <resources>
    <string name="app_name">List Dialog App</string>
    <string name="Select_An_App">Select An App</string>
    <string name="dialogTitle">Choose An App</string>
    <string-array name="apps">
    <item>Adode Dreamweaver</item>
    <item>Adode Photoshop</item>
    <item>Adobe Illustrator</item>
    <item>Adobe Animate</item>
    <item>Adobe After Effects</item>
    <item>Adobe Muse</item>
    <item>Adobe Fuse</item>
    </string-array>

    </resources>

  4. Write the following highlighted code in the MainActivity.java file:

    public class MainActivity extends AppCompatActivity {

    private Button selectApp;
    // Constant to identify the dialog


    private static final int SELECT_APP_DIALOG = 1;
    private String[ ] apps;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

            selectApp = (Button) findViewById(R.id.showListDialogButtonID);
    selectApp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    showDialog(SELECT_APP_DIALOG);
    }
    });
    }

    }

  5. Click OUTSIDE of the onCreate() method closing curly brace and then right-click and select Generate > Override Method… and then under the android.app.Activity class, choose onCreateDialog(id:int):Dialog from the list and then click the OK button.

  6. In the onCreateDialog() method, add the following highlighted switch code:

    protected Dialog onCreateDialog(int id) {
    switch(id) {
    case SELECT_APP_DIALOG:
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.dialogTitle);
    builder.setItems(apps, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(MainActivity.this, apps[which], Toast.LENGTH_SHORT).show();
    }
    });
    return builder.create();
    }
    return super.onCreateDialog(id);
    }

  7. CHECK POINT: Run the app in an emulator and click on the Select An App button. You should see the list dialog displayed. Now, click on one of the list item. You should see a Toast with the name of the selected item.