Dev.Sinto
Dev.Sinto

Reputation: 6852

How can I access the EditText field in a DialogBox?

How can I access the EditText field in a DialogBox?

Upvotes: 5

Views: 5333

Answers (1)

Dennis Winter
Dennis Winter

Reputation: 2037

Place your EditText widget into your dialog:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/myEditText"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" />
</LinearLayout>

Then inflate the View from within your Dialog and get the content of the EditText.

private Dialog myTextDialog() {
    final View layout = View.inflate(this, R.layout.myDialog, null);

    final EditText savedText = ((EditText) layout.findViewById(R.id.myEditText));

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(0);

    builder.setPositiveButton("Save", new Dialog.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
           String myTextString = savedText.getText().toString().trim();
        }
    });
    builder.setView(layout);
    return builder.create();
 }

After pressing the "Save"-button myTextString will hold the content of your EditText. You certainly need to display the dialog of this example first.

Upvotes: 14

Related Questions