对话框中的android edittext返回null

时间:2017-10-19 01:46:00

标签: android android-edittext

现在我感到非常愚蠢,我真的希望能找到像这样的解决方案。

我想做什么:Alert有一个edittext,来自这个edittext的输入将用于下一个活动 我的问题是字符串测试始终为null。我做错了什么?

public void CalibrateButtonClicked(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();

final View dialogView = inflater.inflate(R.layout.dialog, null);
builder.setMessage("calibration");


builder.setView(dialogView)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              //  startActivity(new Intent(FaceMenu.this, FaceTrackerActivity.class));
               EditText edit = (EditText)dialogView.findViewById(R.id.editText2);
                String test= edit.getText().toString();
                Intent intent = new Intent(getBaseContext(), FaceTrackerActivity.class);
                intent.putExtra("EXTRA_SESSION_ID", test);
                startActivity(intent);

            }
        })
        .create().show();
}

2 个答案:

答案 0 :(得分:1)

将您的EditText外部初始化为setPositiveButton

像:

public void CalibrateButtonClicked(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();

final View dialogView = inflater.inflate(R.layout.dialog, null);
final EditText edit = (EditText)dialogView.findViewById(R.id.editText2);

builder.setMessage("calibration");
builder.setView(dialogView)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              //  startActivity(new Intent(FaceMenu.this, FaceTrackerActivity.class));
                String test= edit.getText().toString();
                Intent intent = new Intent(getBaseContext(), FaceTrackerActivity.class);
                intent.putExtra("EXTRA_SESSION_ID", test);
                startActivity(intent);

            }
        })
        .create().show();
}

答案 1 :(得分:0)

您可以尝试将视图绑定放出OnClickListener吗?

public void CalibrateButtonClicked(View v) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    final View dialogView = View.inflate(R.layout.dialog, null);
    EditText edit = (EditText) dialogView.findViewById(R.id.editText2);

    builder.setMessage("calibration");
    builder.setView(dialogView)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            //  startActivity(new Intent(FaceMenu.this, FaceTrackerActivity.class));
            String test= edit.getText().toString();
            Intent intent = new Intent(getBaseContext(), FaceTrackerActivity.class);
            intent.putExtra("EXTRA_SESSION_ID", test);
            startActivity(intent);

          }
        })
        .create().show();
  }