如何从对话框中的edittext获取文本 [英] how to get text from edittext inside a dialog

查看:89
本文介绍了如何从对话框中的edittext获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题所述,如何从自定义对话框中找到的EditText中获取文本?

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

这是我的dialogfragment中的onCreateDialog方法:

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();
}

我无法使它工作..我在edittext中写了一些东西,然后按OK,它崩溃了,并在此行上给了我一个空指针错误:

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());

推荐答案

您正在错误的视图上查找EditText.它不是活动的一部分,而是对话框的一部分.因此,请查看对话框中的视图:

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);

这篇关于如何从对话框中的edittext获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆