how to get text from edittext inside a dialog [duplicate]

一曲冷凌霜 提交于 2019-12-12 01:58:42

问题


Like the title said how can I get text out of EditText which is found inside a custom dialog?

This is the onCreateDialog method from my dialogfragment:

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPref.edit();

    builder.setView(inflater.inflate(R.layout.name_dialog, null))
           .setPositiveButton(R.string.name_ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);
                   editor.putString(getString(R.string.name_key), nameEditText.getText().toString());
                   editor.commit();
               }
           })
           .setNegativeButton(R.string.name_cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   NameDialogFragment.this.getDialog().cancel();
               }
           });      
    return builder.create();
}

I can't get it to work.. I write something in the edittext then i press OK and it just crashes and gives me a null pointer error on this line :

editor.putString(getString(R.string.name_key), nameEditText.getText().toString());

回答1:


You are looking for the EditText at the wrong View. Its not part of the Activity, its part of the dialog. So check the dialog for the view:

 Dialog dialogView = dialog.getDialog();
 EditText paymentEt = (EditText) dialogView.findViewById(R.id.edittext_payment);



回答2:


Instead of using

EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);

try using this

Dialog dialg = (Dialog) dialog;
EditText et = (EditText) dialg.findViewById(R.id.search_input_text);
val = et.getText().toString();


来源:https://stackoverflow.com/questions/26018709/how-to-get-text-from-edittext-inside-a-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!