Edittext(对话框)值为空?

时间:2013-10-06 19:51:24

标签: android dialog android-edittext

我尝试在EditText中使用Dialog。我使用developer.android.com(http://developer.android.com/guide/topics/ui/dialogs.html)中的示例。现在我想按Value时得到EditText的positive Button
我的代码

    public Dialog onCreateDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(main_list.this);
    // Get the layout inflater
   final LayoutInflater inflater = main_list.this.getLayoutInflater();


    builder.setView(inflater.inflate(R.layout.serie_add, null))
            // Add action buttons
            .setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    View promptsView = inflater.inflate(R.layout.serie_add, null);
                    final EditText userInput = (EditText) promptsView
                            .findViewById(R.id.series);

                    Intent intent = new Intent();
                    intent.setClass(main_list.this, add_series.class);
                    intent.putExtra("name", userInput.getText());
                    startActivity(intent);
                }
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    return builder.create();
}

2 个答案:

答案 0 :(得分:1)

正如我所看到的,代码中存在两个问题。 第一个是你在onClick期间给视图充气,所以很明显它是空的。 通货膨胀应该先行,然后你应该在onClick事件上注册。 其次,你正在做:

userInput.getText() instead of
userInput.getText().toString();

答案 1 :(得分:0)

将您的代码重写为:

public Dialog onCreateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(main_list.this);
// Get the layout inflater
final LayoutInflater inflater = main_list.this.getLayoutInflater();

View view = inflater.inflate(R.layout.serie_add, null);
final EditText userInput = (EditText) view
                        .findViewById(R.id.series);

builder.setView(view)
        // Add action buttons
        .setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                View promptsView = inflater.inflate(R.layout.serie_add, null);


                Intent intent = new Intent();
                intent.setClass(main_list.this, add_series.class);
                intent.putExtra("name", userInput.getText().toString());
                startActivity(intent);
            }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

            }
        });
return builder.create();
}