Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an EditText to a DialogFragment?

I have created a DialogFragment and I would like to add an EditText but when I try and add it like this:

final EditText input = new EditText(this);

I get an error on the "this" saying "The constructor EditText(EncryptionDialogFragment) is undefined".

My ultimate goal is to have the user enter their 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();
} 

}

like image 376
GreekOphion Avatar asked Dec 24 '12 16:12

GreekOphion


People also ask

What is the difference between dialog & DialogFragment?

Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.

Is DialogFragment deprecated?

This method is deprecated. androidx.


1 Answers

Use getActivity()

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

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

like image 166
nandeesh Avatar answered Sep 19 '22 05:09

nandeesh