我正在遷移我的對話框(當前使用Activity.showDialog(DIALOG_ID);
)以使用android reference中討論的DialogFragment
系統。定位更改時的DialogFragment回調
有使用回調時提供一些事件回活動/片段打開的對話框我的發展過程中產生了一個問題:
這裏有一個簡單的對話框的一些示例代碼:
public class DialogTest extends DialogFragment {
public interface DialogTestListener {
public void onDialogPositiveClick(DialogFragment dialog);
}
// Use this instance of the interface to deliver action events
static DialogTestListener mListener;
public static DialogTest newInstance(Activity activity, int titleId, int messageId) {
udateListener(activity);
DialogTest frag = new DialogTest();
Bundle args = new Bundle();
args.putInt("titleId", titleId);
args.putInt("messageId", messageId);
frag.setArguments(args);
return frag;
}
public static void udateListener(Activity activity) {
try {
// Instantiate the NoticeDialogListener so we can send events with it
mListener = (DialogTestListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString() + " must implement DialogTestListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int titleId = getArguments().getInt("titleId");
int messageId = getArguments().getInt("messageId");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// dialog title
builder.setTitle(titleId);
// dialog message
builder.setMessage(messageId);
// dialog negative button
builder.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}});
// dialog positive button
builder.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogTest.this);
}});
// create the Dialog object and return it
return builder.create();
}}
這裏有一些活動代碼叫它:
public class SomeActivity extends FragmentActivity implements DialogTestListener {
private EditText mUserName;
@Override
public void onCreate(Bundle savedInstanceState) {
// setup ui
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_user_edit);
// name input
mUserName = (EditText) findViewById(R.id.userEdit_editTextName);
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
Log.d(TAG, this.toString());
mUserName.setText(mUserName.getText() + "1");
}
private void showDialog() {
DialogTest test = DialogTest.newInstance(SomeActivity.this, R.string.someTitleText, R.string.someMessageText);
test.show(getSupportFragmentManager(), "testDialog");
}}
代碼幾乎是你看到的參考。問題是,一旦你做了一個方向改變,當顯示一個對話框時,它會按預期停止工作 - >由於活動的生命週期,活動和對話框都被重建,而對話框現在沒有合適的參考新的重建活動。
我下面的代碼添加到我的activitys的onResume方法:
@Override
protected void onResume() {
super.onResume();
DialogTest.udateListener(this);
}
這樣做,我得到預期的行爲,並在對話框發送事件回新改建活動時的方向發生變化。
我的問題是: 什麼是'最佳實踐'來處理由FragmentActivity在方向更改期間打開的DialogFragment之間的回調?
問候
聽起來像你已經倒下了許多片段陷阱。我遇到同樣的問題,因爲我可以在閱讀這篇優秀的文章的同時修復它:http://code.hootsuite.com/orientation-changes-on-android/。 –