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

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

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