How To Store Edit Text Data From An Android Dialog?
I've set up an alert dialog with multiple edit texts but I'm not sure how to store the values being entered in the alert dialog. Usually I could just do something along the lines o
Solution 1:
Add an interface to your MyMessageDialog class to pass the values back:
publicinterfaceMyMessageDialogListener{
publicvoid onClosed(String ship, String scientist, String email, String volume, String color);
}
Store the dialog layout when you create it and extract the EditText values and pass them back via the listener inside the OK button onClick:
publicclassMyMessageDialog {
publicinterfaceMyMessageDialogListener {
publicvoidonClosed(String ship, String scientist, String email, String volume, String color);
}
@SuppressLint("NewApi")publicstatic AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){
AlertDialog.Builderbuilder=newAlertDialog.Builder(context);
LayoutInflaterinflater= LayoutInflater.from(context);
builder.setTitle(title);
builder.setMessage(message);
finalViewlayoutView= inflater.inflate(R.layout.custom_view, null);
builder.setView(layoutView);
builder.setPositiveButton("Ok", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
// get the edit text values here and pass them back via the listenerif(listener != null)
{
EditTexttext1= (EditText)layoutView.findViewById(R.id.shipNameEditText);
EditTexttext2= (EditText)layoutView.findViewById(R.id.scientistEditText2);
EditTexttext3= (EditText)layoutView.findViewById(R.id.emailEditText3);
EditTexttext4= (EditText)layoutView.findViewById(R.id.volumeEditText4);
EditTexttext5= (EditText)layoutView.findViewById(R.id.colourEditText4);
listener.onClosed(text1.getText().toString(),
text2.getText().toString(),
text3.getText().toString(),
text4.getText().toString(),
text5.getText().toString());
}
dialog.cancel();
}
});
builder.show();
return builder.create();
}
}
Create an instance of the listener when you call the dialog and use it to receive the strings:
MyMessageDialog.displayMessage(SearchResult.this, "Sample Info", "Required",
newMyMessageDialog.MyMessageDialogListener() {
publicvoidonClosed(String ship, String scientist, String email, String volume, String color)
{
// store / use the values here
}
});
Post a Comment for "How To Store Edit Text Data From An Android Dialog?"