我无法让 AlertDialog 将文本传递回调用它的活动。似乎问题是调用 findViewByID 时找不到正确的 EditText,但我是 Android 新手,不知道为什么会这样。
代码如下:
public class ModifyDialogFragment 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 MDialogListener {
public void onMDialogPositiveClick(String newValue);
}
// Use this instance of the interface to deliver action events
MDialogListener mListener;
String mEntryName = "";
EditText mEditText;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View modifyView = inflater.inflate(R.layout.modify_dialog, null);
builder.setView(modifyView);
final EditText editText = (EditText) getActivity().findViewById(R.id.modificationText);
builder.setPositiveButton(R.string.modify, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onMDialogPositiveClick(editText.getText().toString());
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
// Override the Fragment.onAttach() method to instantiate the ModifyDeleteDialogListener
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the MDDialogListener so we can send events to the host
mListener = (MDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement MDialogListener");
}
}
以及对应的 modify_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/modificationText"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"/>
为什么找不到editText?我可以做些什么来使这项工作按预期工作,将新字符串传递回活动?