I am using an AlertDialog.Builder to display a dialog to prompt the user to enter a password, I then want to save that password in a preference, however I can't figure out how to get the result from the alert dialog's input method.
Here is essentially what I would like to be able to do:
String result; AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Please enter a password"); final EditText input = new EditText(this); b.setView(input); b.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { //I get a compile error here, it wants result to be final. result = input.getText().toString(); } }); b.setNegativeButton("CANCEL", null); b.create().show();
However, I am open to doing something such as showDialog(int);
then using the onCreateDialog(int)
method and somehow setting the result and receiving it in some other method, but I have no idea how to go about the last part.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog. A dialog with a pre-defined UI that allows the user to select a date or time.
AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .
The way to make a checkbox list is to use setMultiChoiceItems . // setup the alert builder AlertDialog. Builder builder = new AlertDialog. Builder(context); builder.
public class MyActivity extends Activity { private String result; void showDialog() { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Please enter a password"); final EditText input = new EditText(this); b.setView(input); b.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { result = input.getText().toString(); } }); b.setNegativeButton("CANCEL", null); b.show(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With