How can I access the EditText field in a dialog box?

How can I access the EditText field in a DialogBox?

+4
source share
1 answer

Place the EditText widget in 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 your dialog and get the contents 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 clicking the Save button, myTextString will save the contents of your EditText. You must first display the dialog for this example.

+13
source

All Articles