Reputation: 953
I want to build a function that creates an AlertDialog and returns the string that the user entered, this the function I have for creating the dialog, how do I return the value?
String m_Text = "";
private String openDialog(String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
// return string
}
Upvotes: 6
Views: 4565
Reputation: 4926
The call builder.show()
which opens your AlertDialog
is not a blocking call. In other words, the subsequent instructions will be executed without waiting for the AlertDialog
to finish (return). You should interact with it by using some callback. For instance, your OnClickListeners
are an implementation of such a pattern.
One clean way to achieve what you want is to create a Functional Interface which is an interface having only one method. You would use it for handling your callbacks.
interface OnOK{
void onTextEntered(String text);
}
And then you would alter your method to be like:
private void openDialog(String title, final OnOK onOK) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Oi, look at this line!
onOK.onTextEntered(input.getText().toString());
}
});
builder.show();
}
You can use it like this:
openDialog("Title", new OnOK() {
@Override
onTextEntered(String text) {
Log.i("LOG", text);
}
});
Upvotes: 12
Reputation: 678
This looks to me like you have stored the value of the inputted text in the m_Text field. You can either just return that field or have a variable within the function in which you store the value to be returned.
Where you have:
//Return string
simply replacing with:
return m_Text;
should do the job.
Upvotes: 0
Reputation: 323
Create another method in the same class that accepts a string value, then call that function providing the value of input.getText().toString()
from your setPositiveButton
onclick event
Upvotes: -1