2012-01-26 45 views
3

我正在使用自定义的DialogFragment来让用户更改其登录凭据。有一些文本字段和两个按钮(保存/取消)。布局在DialogFragment的onCreateView方法中设置。重置Android DialogFragment

如果我打开对话框文本字段填充了默认值。当用户更改文本字段中的文本并单击取消按钮时,该对话框将被解除。下一次对话框打开时,之前更改的文本字段不包含默认值,而是包含用户之前更改过的文本。文本字段不会重置。这几乎是在这里提到的相同问题Reset an Android Dialog。问题是提供的解决方案引用了API级别11中弃用的Dialog,并且我无法将OnPrepareDialog与DialogFragment一起使用。

有没有类似的方法来重置DialogFragment的内容?

+0

我有相反的问题。出于某种原因,我无法在对话结束后保留​​对话内容。你能解释你是怎么做到的? – njzk2

回答

5

你可以在你的类,它扩展DialogFragmet覆盖的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() 
    } 
} 
0

您还可以使用.setText()方法在你的活动为负号按钮点击后的反应。例如: 在DialogFragment.java,onCreateDialog(...)限定AlertDialog.Builder

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 
}