findViewById从AlertDialog(含自定义布局) - NullPointerException异常 [英] findViewById from AlertDialog (with Custom Layout) - NullPointerException

查看:169
本文介绍了findViewById从AlertDialog(含自定义布局) - NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让文本从一个AlertDialog,这是建立在EditTexts,因为你可以看到下面。问题是,我不能检索textviews。我得到的是一个空值。有任何想法吗?

I’m trying to get the text out of EditTexts within an AlertDialog, which is created as you can see below. The problem is, that I can’t retrieve the textviews. All I get is a null-value. Any ideas?

    final EditText editFirstname = (EditText) findViewById(R.id.editFirstname);
    final EditText editLastname = (EditText) findViewById(R.id.editLastname);

    bttAddPlayer.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            builder.setView(layoutInflater.inflate(R.layout.dialog_add_player, null))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            databaseHelper.addPlayer(editFirstname.getText().toString(),editLastname.getText().toString());
                            playerAdapter.notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    });
}

}

推荐答案

您需要你夸大你的警报对话框查看里面搜索,说你夸大的观点如下:

You need to search inside of the View that you inflate for your Alert dialog, say that the view you inflate is as follows:

    View view = inflater.inflate(R.layout.dialog_add_player, container);

那么你就需要做

EditText editFirstName = (EditText) view.findViewById(R.id.editFirstName);
EditText editLastName  = (EditText) view.findViewById(R.id.editLastName);

看起来现在你正试图实例化一个变量的东西不存在,你有没有在那里的的EditText 实际位于它试图引用看看目前看来,它不包含在的EditText

It looks like right now you are trying to instantiate a variable for something that does not exist, you have no reference of where the EditText is actually located, it's trying to look inside of the current view, which does not contain the EditText.

这篇关于findViewById从AlertDialog(含自定义布局) - NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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