1

我试图用一个对话框提示用户,该对话框包含两个 EditText 框,一个正面和负面按钮。我遇到的问题是尝试从 EditText 框中检索值时出现空指针异常。这是我的代码,

            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);

            LayoutInflater inflater = LayoutInflater.from(context);
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("New Location");
            builder.setView(inflater.inflate(R.layout.new_location_dialog, null)); 

            final EditText titleBox = (EditText)findViewById(R.id.title);
            final EditText descriptionBox = (EditText)findViewById(R.id.description);             

            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int button) {

                    String title = titleBox.getText().toString();
                    String description = descriptionBox.getText().toString();
                    Log.d("User Setting title / description to: ", title + " : " + description);

                    //Add new Point to Map
                    addGeoPointToMap(mapOverlays,longpressLocation,title, description);    

                    return;
                }
            });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Log.d("Cancel setting Title & adding point","");
                    return;
                }
            });
            builder.show();

如果有人能帮我一把,我将不胜感激!此外,如果有人可以解释在整个应用程序中处理多个对话框的最佳约定是什么,则加分。

4

1 回答 1

7

您没有正确引用 EditText 对象。

执行以下操作,它将起作用:

View v = inflater.inflate(R.layout.new_location_dialog, null);
builder.setView(v); 

//here is your mistake:

final EditText titleBox = (EditText)v.findViewById(R.id.title);
final EditText descriptionBox = (EditText)v.findViewById(R.id.description);    
于 2012-10-16T15:46:26.177 回答