Android: Allow user to edit/input text from an alert dialog

0 Comments

This little snippet is a simple one, but it makes the user experience a whole lot better.

Instead of implementing a new Activity/screen to enter in some text, just make it an AlertDialog() with an EditText view.

01.final EditText txtUrl = new EditText(this);
02. 
03.// Set the default text to a link of the Queen
05. 
06.new AlertDialog.Builder(this)
07.  .setTitle("Moustachify Link")
08.  .setMessage("Paste in the link of an image to moustachify!")
09.  .setView(txtUrl)
10.  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
11.    public void onClick(DialogInterface dialog, int whichButton) {
12.      String url = txtUrl.getText().toString();
13.      moustachify(null, url);
14.    }
15.  })
16.  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
17.    public void onClick(DialogInterface dialog, int whichButton) {
18.    }
19.  })
20.  .show();

This does all the magic. The example shows you how to:

  • Create the edit textfield and assign some properties
  • Build the dialog
  • Set the title/message for the dialog
  • Embed the text field
  • Do something after the user clicks OK or Cancel

Obviously you're gonna have to fill the positive button action with your own intentions.

Have fun!

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog