Main Tutorials

Android prompt user input dialog example

In this tutorial, we will enchance the previous AlertDialog example, to make it able to accept user input, just like a PromptDialog. More specific, this is a custom AlertDialog example.

See following steps :

  1. Create a prompt dialog layout (XML file).
  2. Attach the prompt dialog layout to AlertDialog.Builder.
  3. Attach the AlertDialog.Builder to AlertDialog.
  4. Done.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

Note
You may interest to read this custom dialog example.

1 Android Layout Files

Two XML files, one for main screen, one for prompt dialog.

File : res/layout/main.xml


<?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/buttonPrompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Prompt Dialog" />

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

    </EditText>
            
</LinearLayout>

File : res/layout/prompts.xml


<?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/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Type Your Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextDialogUserInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />

    </EditText>

</LinearLayout>

2. Activity

Read the comment and demo in next step, it should be self-explorary.

File : MainActivity.java


package com.mkyong.android;

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 {

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

	public void onCreate(Bundle savedInstanceState) {

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

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

		// add button listener
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				// get prompts.xml view
				LayoutInflater li = LayoutInflater.from(context);
				View promptsView = li.inflate(R.layout.prompts, null);

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

				// set prompts.xml to alertdialog builder
				alertDialogBuilder.setView(promptsView);

				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.editTextDialogUserInput);

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

				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();

				// show it
				alertDialog.show();

			}
		});
	}
}

3. Demo

Start it, the “main.xml” layout is display a button and edittext (result).

android prompt user input example

Click on the button, display a prompt dialog “prompts.xml” layout, type message “mkyong“, and click on the “OK” button.

android prompt user input example

User input “mkyong” will pass to the “main.xml” layout, edittext (result), and display it.

android prompt user input example

Download Source Code

Download it – Android-Prompt-Dialog-Example.zip (16 KB)

References

  1. Android AlertDialog Javadoc
  2. Android Dialog example
  3. Android custom dialog example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
32 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Max Tomlinson
10 years ago

Great demo – thanks for posting

Selva
2 years ago

This really helps me. Thank you..

Abdul Waheed
3 years ago

Great code Thank you so much

Sajan
5 years ago

very good highly help full,thanks a lot

Lougen Magbanua
5 years ago

how to use this in adapter?

Dian Putra
5 years ago

Thank You So Much.

Safiya Akhtar
5 years ago

thanks

Frans Appel
8 years ago

Worked. Thank you.

Dani
8 years ago

I understood everything but i have one question. How can i disable the “OK” Button if there is nothing in the userInput?

Mayank Tripathi
9 years ago

nice article !!

Sanchez
9 years ago

thank you for the tutorial

Sulaiman
9 years ago

Nice tutorial

Evan Pu
9 years ago

concise and to the point as usual. great work

Ricky
10 years ago

sir please show us the advance coding for android

Bharat Patidar
10 years ago

Thank you very much for help, You make my day.

R2
10 years ago

NICE share bro, your article help me to solve problem i got when handling pop up with input dialog 😀

K.Dam
10 years ago

Thanks for the articles. I’ve found a lot of interesting and useful things about android here!

faeze_el
10 years ago

great tutorial,like the previous ones.
thanks a lot.

Dode
10 years ago

Thank you sir, this post help me alot 😀

Hardik
10 years ago

Thank you very much for all of these awesome tutorials… They have helped me very much.. Keep up this awesome work..

kingdom and dragons hacks
10 years ago

Hey there would you mind letting me know
which web host you’re working with? I’ve loaded your blog in 3 different browsers and I must say
this blog loads a lot faster then most. Can you recommend a
good hosting provider at a fair price? Many thanks, I appreciate it!

nel
10 years ago

Thank you very much.. Simple and understandable.. Suits for all beginners

Azmi
11 years ago

Can you please explain how can i get java to read an XML file, also how can i make the program to prompt user for files from XML and display them after?? I would be really thankful if you/anyone could help me??

Droidster
11 years ago

FINALLY! Unlike so many sites with assuemed knowledge tutorials, this one has it down for anyone to try! THANK YOU!!

Shalgham
11 years ago

really thanks it’s helped

vraa
11 years ago

Thanks, reading values from inflated custom layout can be a bit tricky..if you try to use findViewById without referencing to the inflated view.

Nizzy
11 years ago

I keep coming here to copy codes for my Android project. Today, I just want to say Thank You.

Pritam
11 years ago

Very great tutorial … can u plz give the example of custom dialog with “textview” and
“edittext” and a “Button” something should be happen when udser clicks on the button

Mahesh
9 years ago
Reply to  Pritam

hii how to runtime set edittext or textview value from sting in this promptview dialog

Example :

final EditText editusername = (EditText) promptsView.findViewById(R.id.editusername);
editusername.settext(username);

when i set like this it gives me error

06-11 08:47:40.242: E/AndroidRuntime(22247): FATAL EXCEPTION: main
06-11 08:47:40.242: E/AndroidRuntime(22247): java.lang.NullPointerException
06-11 08:47:40.242: E/AndroidRuntime(22247): at com.montor.werbungstudio.HomeActivityNew$3.onClick(HomeActivityNew.java:498)
06-11 08:47:40.242: E/AndroidRuntime(22247): at android.view.View.performClick(View.java:4274)
06-11 08:47:40.242: E/AndroidRuntime(22247): at android.view.View$PerformClick.run(View.java:17357)
06-11 08:47:40.242: E/AndroidRuntime(22247): at android.os.Handler.handleCallback(Handler.java:615)
06-11 08:47:40.242: E/AndroidRuntime(22247): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 08:47:40.242: E/AndroidRuntime(22247): at android.os.Looper.loop(Looper.java:137)
06-11 08:47:40.242: E/AndroidRuntime(22247): at android.app.ActivityThread.main(ActivityThread.java:4949)
06-11 08:47:40.242: E/AndroidRuntime(22247): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 08:47:40.242: E/AndroidRuntime(22247): at java.lang.reflect.Method.invoke(Method.java:511)
06-11 08:47:40.242: E/AndroidRuntime(22247): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
06-11 08:47:40.242: E/AndroidRuntime(22247): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
06-11 08:47:40.242: E/AndroidRuntime(22247): at dalvik.system.NativeStart.main(Native Method)

kichu
9 years ago
Reply to  Mahesh

Hi Have u solved this issue…
If yes,please let me know how u fixed it…??
Thanks in advance….

Mahesh
9 years ago
Reply to  kichu

final TextView textuser=(TextView)promptsView.findViewById(R.id.textuser);
final EditText editpassword = (EditText) promptsView.findViewById(R.id.editpassword);
String currentuser=”E-Mail: “+susername;
textuser.setText(currentuser);

share your code here if it is not working

Gregor
8 years ago

Your code is working ok under such simple and unlikely situations.
But what do I have to do if (in more complicated and realistic situations) I need to know the answer of the user to continue for instance “continue yes / no”. The .show() doesn’t wait, the code after it is executed before the dialog shows and the user answers.