重置Android DialogFragment

4
我正在使用自定义的DialogFragment来让用户更改他的登录凭据。有一些文本字段和两个按钮(保存/取消)。布局在DialogFragment的onCreateView方法中设置。
如果我打开对话框,文本字段会填充默认值。当用户更改文本字段中的文本并单击取消按钮时,对话框将被关闭。下次打开对话框时,先前更改的文本字段不包含我期望的默认值,而是包含了用户之前更改的文本。文本字段未重置。这几乎是在Reset an Android Dialog中提到的相同问题。问题在于所提供的解决方案是针对API级别11中已过时的Dialog而言的,并且我无法使用onPrepareDialog来处理DialogFragment。
是否有类似的方法可以重置DialogFragment的内容?

我有相反的问题。由于某种原因,我无法在对话框关闭后保留其内容。您能解释一下您是如何做到的吗? - njzk2
2个回答

6
您可以在扩展DialogFragment的类中覆盖onResume()方法,如下所示:
private static class MyDialogFragment extends DialogFragment {
  public static MyDialogFragment newInstance() {
    // ...
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // ...
  }

  @Override
  public void onResume() {
    super.onResume();
    Dialog dialog = getDialog();
    // reset code goes here - use dialog as you would have in onPrepareDialog()
  }
}

你好,我想问为什么onResume没问题但onViewCreated却不行,尽管viewcreated函数已经被调用了? - user3900009

0
您还可以在您的活动中使用.setText() 方法作为负按钮点击后的反应。例如:在 DialogFragment.java 中,定义AlertDialog.Builder 在onCreateDialog(...)中。
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

那么

//this is better than creating button in layout
builder.setNegativeButton(R.string.button_cancel,
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            ((MainAct) getActivity()).cancelDialog(DialogFragment.this);
        }
    }
);

在MainActivity.java中创建方法cancelDialog(DialogFragment df) {。
//here use df to reset text fields
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接