這是我認爲解決的最佳方式,並使用下面的方法的問題:
創建一個靜態方法來初始化一個對話框,記住,這是一個很好的做法,因爲我們總是有默認的構造函數和Bundle存儲Fragment的狀態。 在onCreateDialog方法中,使用在「構造函數方法」中傳遞的數據初始化AlertDialog。 在你的活動中,你可以實現一個接口(因爲我們不能保存它的引用,因爲它可能在旋轉設備時被破壞)。要打開對話框, 檢查它已被添加到FragmentManager中否則會顯示。
多看這裏(葡萄牙文鏈接 - BR):http://nglauber.blogspot.com.br/2013_10_01_archive.html
public class SimpleDialog extends DialogFragment implements OnClickListener {
private static final String EXTRA_ID = "id";
private static final String EXTRA_MESSAGE = "message";
private static final String EXTRA_TITLE = "title";
private static final String EXTRA_BUTTONS = "buttons";
private static final String DIALOG_TAG = "SimpleDialog";
private int dialogId;
public static SimpleDialog newDialog(int id,
String title, String message, int[] buttonTexts){
// Using the Bundle to save state
Bundle bundle = new Bundle();
bundle.putInt(EXTRA_ID, id);
bundle.putString(EXTRA_TITLE, title);
bundle.putString(EXTRA_MESSAGE, message);
bundle.putIntArray(EXTRA_BUTTONS, buttonTexts);
SimpleDialog dialog = new SimpleDialog();
dialog.setArguments(bundle);
return dialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments() .getString(EXTRA_TITLE);
String message = getArguments().getString(EXTRA_MESSAGE);
int[] buttons = getArguments().getIntArray(EXTRA_BUTTONS);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(message);
switch (buttons.length) {
case 3:
alertDialogBuilder.setNeutralButton(buttons[2], this);
case 2:
alertDialogBuilder.setNegativeButton(buttons[1], this);
case 1:
alertDialogBuilder.setPositiveButton(buttons[0], this);
}
return alertDialogBuilder.create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
// Your Activity must to implements this interface
((FragmentDialogInterface)getActivity()).onClick(dialogId, which);
}
public void openDialog(FragmentManager supportFragmentManager) {
if (supportFragmentManager.findFragmentByTag(DIALOG_TAG) == null){
show(supportFragmentManager, DIALOG_TAG);
}
}
// Interface that was invoked by clicking the button
public interface FragmentDialogInterface {
void onClick(int id, int which);
}
要在活動
public void openSimpleDialog(View v) {
SimpleDialog dialog = SimpleDialog.newDialog(
0, // Id from dialog
"Alert", // title
"Message", // menssage
new int[]{ // texts from buttons
android.R.string.ok,
android.R.string.cancel });
dialog.openDialog(getSupportFragmentManager());
}
@Override
public void onClick(int id, int which) {
Toast.makeText(MainActivity.this,
"Button clicked"+ which, Toast.LENGTH_SHORT)
.show();
}
如果我正確記得是正常行爲。我通常爲show方法提供一個標籤,當再次調用Activity的onCreate時,我查找標籤。如果片段!= null,我創建一個新實例並再次顯示 – Blackbelt
@blackbelt,但片段!= null假定已經有一個帶有此標記的片段。如果再次添加相同的片段,舊的片段是否仍然在視圖層次結構中? –
是的,它的確如此。刪除它之前,顯示新的,因爲你需要片段管理器來顯示對話框片段,我不知道它是否被綁定到活動的實例, – Blackbelt