AlertDialog

Android Prompt User Input Dialog Example

In Android you can use the AlertDialog component, and you can customize it to your own User Interface so it can have any use you want. In this tutorial we are going to create an AlertDialog that can accept text input for the user. As we know there is no such thing by default. That means we have to make it ourselves. To do this, we will :

  1. Create a new xml layout file.
  2. Bundle the new layout file with the View of the AlertDialog Box

 

 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">PromptDialogExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="tv_label">Type Your Message : </string>
    <string name="button_label">Show Prompt Dialog</string>

</resources>

So, we’ve just created some string resources that we can use in many ways and in many places in our app.

3. Create the main layout of the Application

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_label" />

    <EditText
        android:id="@+id/editTextResult"
        android:layout_width="match_parent"
        android:inputType="text"
        android:layout_height="wrap_content" >

    </EditText>

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

4. Create a new layout for the Prompt Dialog Box

In Android, there is no Alert Box that accepts user input by default. So, we have to make it ourselves. For example we want the Alert Dialog Box to contain an EditText component. And for that we need to create an new layout xml file. The Alert Dialog Box will be created according to the new layout file that we will create. To create a new layout file, go to the Package Explorer and right click on the res/layout folder. Select New -> Other -> Android -> Android XML Layout File. And click Next:

Then specify the name of the file and the Layout type and click Finish:

As you will see in the Package Explorer the new /res/layout/prompts.xml file has been created:

Open that file and paste the following code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_label"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/userInput"
        android:layout_width="match_parent"
        android:inputType="text"
        android:layout_height="wrap_content" >

        <requestFocus />

    </EditText>

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

Don’t forget that we will use this layout for our Alert Dialog Box.

5. Code

The code of this tutorial is pretty much self explanatory. The interesting part is how to tell the Alert Dialog Box to use the new xml file as its layout description. Go to the java file that contains the code of the activity you’ve just created and paste the following code:

package com.javacodegeeks.android.promptdialogexample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	private Button button;
	private EditText editTextMainScreen;
	final Context context = this;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// components from main.xml
		button = (Button) findViewById(R.id.button);
		editTextMainScreen = (EditText) findViewById(R.id.editTextResult);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				// get prompts.xml view
				LayoutInflater layoutInflater = LayoutInflater.from(context);

				View promptView = layoutInflater.inflate(R.layout.prompts, null);

				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

				// set prompts.xml to be the layout file of the alertdialog builder
				alertDialogBuilder.setView(promptView);

				final EditText input = (EditText) promptView.findViewById(R.id.userInput);

				// setup a dialog window
				alertDialogBuilder
						.setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										// get user input and set it to result
										editTextMainScreen.setText(input.getText());
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,	int id) {
										dialog.cancel();
									}
								});

				// create an alert dialog
				AlertDialog alertD = alertDialogBuilder.create();

				alertD.show();

			}
		});
	}
}

As you can see we use a LayoutInflater to create an new View that will use the prompts.xml file as the layout description. And when we do : alertDialogBuilder.setView(promptView), we setup the Alert Dialog Box to use the newly created View as its User Interface.

6. Run the application

This is the main screen of our Application:

Now, when you press the button, the Dialog Box will pop up. Now we can type our input in the Text Filed :

If you press “No”, you will go back to the application. In this case, you will go back to the main screen of the application. But if you press “OK” you will see that your input will be displayed on the main screen:

Download Eclipse Project

This was an Android Prompt User Input Dialog Example. Download the Eclipse Project of this tutorial: AndroidPromptDialogExample.zip

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button