How to add EditText to DialogFragment?

I created a DialogFragment and I would like to add an EditText, but when I try to add it as follows:

final EditText input = new EditText(this); 

I get the error "this": "Constructor EditText (EncryptionDialogFragment) - undefined".

My ultimate goal is to enter the password this way.

 public class EncryptionDialogFragment extends DialogFragment { final EditText input = new EditText(this); static EncryptionDialogFragment newInstance(String title){ EncryptionDialogFragment fragment = new EncryptionDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setIcon(R.drawable.ic_launcher) .setTitle("Enter Password:") .setView(input) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ((MainActivity)getActivity()).doPositiveClick(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ((MainActivity)getActivity()).doNegativeClick(); } }).create(); } 

}

+6
source share
2 answers

Use getActivity ()

 final EditText input = new EditText(getActivity()); 

and do not use it in the field, initialize it in onCreateView, where getActivity will not return null

+6
source

this should be a Context, that is, Management. You cannot create an EditText before your fragment is attached to the action. In onCreateDialog you can do new EditText(getActivity()) .

+1
source

All Articles