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

5 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.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
.setTitle("Moustachify Link")
.setMessage("Paste in the link of an image to moustachify!")
.setView(txtUrl)
.setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String url = txtUrl.getText().toString();
moustachify(null, url);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.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

5 comments:

  1. Very simple yet effective. I never even thought about passing an EditText as a view to an AlertDialog before. Saves the effort creating a Custom Dialog. Mnay thanks

    ReplyDelete
    Replies
    1. You're welcome! I guess it's something I brought over from years of doing desktop dev lol

      Delete
  2. I have a problem with the code. Im using an alert to show a edittext where the user put a string to search in a database. The first time work fine, but the second throws:

    AndroidRuntime(14168): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

    ¿What can i do?

    ReplyDelete
    Replies
    1. Don't reuse the EditText. Either recreate it each time the AlertDialog is shown, or remove the view from the parent layout first.

      Delete
  3. This is a great, easy to implement solution; thanks!

    ReplyDelete

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

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