无法将字符串对象从 DialogFragment 传递到 MainActivity

Failed to pass String object from DialogFragment to MainActivity

我创建了一个 DialogFragment [实现为 AlertDialogOnCreateDialog(Bundle)]。

DialogFragment 要求用户通过 EditText 框输入项目名称 (String),我正试图将其传回给 MainActivity

MainActivity 中,我使用 Toast 来检查 String 是否确实已传递。由于未通过任何检查,此检查失败。但是,如果我在 DialogFragment 中对字符串进行硬编码,它就可以工作。这让我怀疑我尝试定位 EditText 对象的方式有问题,但我不确定我的错误是什么。

MainActivity.java

public class MainActivity extends AppCompatActivity  implements NewProjectDialog.NewProjectDialogListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //initialize the two on screen buttons
    //onclick listeners are attached to activity_main.xml
    Button newProject = (Button) findViewById(R.id.new_project);
    Button browseProjects = (Button) findViewById(R.id.browse_projects);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void newProject(View view) {
    //Open up the DialogFragment that prompts user for the title
    DialogFragment newFragment = new NewProjectDialog();
    newFragment.show(getFragmentManager(), "New Project Dialog");
}

@Override
public void onDialogOK(String projectTitle) {
    //Toast.makeText(MainActivity.this, projectTitle, Toast.LENGTH_SHORT).show();

}

@Override
public void onDialogCancel() {
    //user pressed cancel in NewProjectDialog
    Toast.makeText(MainActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
}

public void browseProjects(View view){
    Toast.makeText(MainActivity.this, "Browse Projects", Toast.LENGTH_SHORT).show();
}

NewProjectDialog.java

public class NewProjectDialog extends DialogFragment{

/* The activity that creates an instance of this dialog fragment must
 * implement this interface in order to receive event callbacks.
 * Each method passes the DialogFragment in case the host needs to query it. */
public interface NewProjectDialogListener {
    public void onDialogOK(String projectTitle);
    public void onDialogCancel();
}

// Use this instance of the interface to deliver action events
NewProjectDialogListener mListener;

// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeDialogListener so we can send events to the host
        mListener = (NewProjectDialogListener) activity;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
    }
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder newProjectDialog = new AlertDialog.Builder(getActivity());

   //prevent dialog from closing
    setCancelable(false);

   //set dialog title
    newProjectDialog.setTitle(R.string.new_project_title);

    //inflate view so that findViewbyId on the next line works
    View view = View.inflate(getActivity(),R.layout.new_project_dialog, null);
    //Link tempEdit object to the text-edit box so we can retrieve data from it below upon button click
    final EditText tempEdit = (EditText)view.findViewById(R.id.project_title);

    //set the view
    newProjectDialog.setView(R.layout.new_project_dialog);

    //set OK button
    newProjectDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //Toast.makeText(getActivity(), tempEdit.getText().toString(), Toast.LENGTH_SHORT).show();
            mListener.onDialogOK(tempEdit.getText().toString());
        }
    });

    //set cancel button
    newProjectDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            mListener.onDialogCancel();
        }
    });

    // Create the AlertDialog object and return it
    return newProjectDialog.create();
}

你是对的,问题是你从不同的角度看待EditText。因为你的布局被膨胀了两次。

尝试使用 setView(View) 而不是带有 layout resource id 的那个。