来自AlertDialog的findViewById(带有自定义布局) - NullPointerException

时间:2014-06-30 20:09:37

标签: android

我正在尝试从AlertDialog中的EditTexts中获取文本,这可以在下面看到创建。问题是,我无法检索textviews。我得到的只是一个空值。有任何想法吗?

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

}

1 个答案:

答案 0 :(得分:3)

您需要在视图内搜索您为“警报”对话框充气,例如您膨胀的视图如下:

    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