首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NullPointerException in DialogFragment

NullPointerException in DialogFragment
EN

Stack Overflow用户
提问于 2015-02-27 14:11:55
回答 6查看 564关注 0票数 1

当我点击我的NullPointerException的正面按钮时,我的DialogFragment出现了一些问题。我设置了一个主要由EditText组成的布局,我正在应用程序中使用它们的内容。当应用程序试图检索EditText的内容时,会出现问题。

在我的MainActivity中,我在一个Button上设置了一个侦听器,它用show()方法调用DialogFragment。下面是描述我的DialogFragment的代码片段

代码语言:javascript
复制
private class PersonalInfoDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.personalinformation)
               .setView(inflater.inflate(R.layout.personalinformation_dialog, null))
               .setPositiveButton(R.string.edit, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {

                        EditText name_options = (EditText) findViewById(R.id.name_options);
                        //This line makes the app crash:
                        String text = name_options.getText().toString();
                        //doing some job...
                       }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancelled the dialog
                   }
               });
        // Create the AlertDialog object and return it
        return builder.create();
    }

为什么会有这种例外呢?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2015-02-27 14:18:41

使用您要传递给setViewView对象,以便从Dialog布局访问EditText。以下列方式进行:

代码语言:javascript
复制
final View view=inflater.inflate(R.layout.personalinformation_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.personalinformation)
               .setView(view)
               ....

获取EditText用于onClick方法中的对话框:

代码语言:javascript
复制
EditText name_options = (EditText)view. findViewById(R.id.name_options);
票数 1
EN

Stack Overflow用户

发布于 2015-02-27 14:17:57

兄弟..。初始化xml控制器时,请使用以下命令

代码语言:javascript
复制
yourview.findViewById(R.id.name_options);
票数 3
EN

Stack Overflow用户

发布于 2015-02-27 14:38:21

我认为你应该用这个:

代码语言:javascript
复制
EditText name_options = (EditText) getDialog().findViewById(R.id.name_options); 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28767080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档