Tôi đã gặp phải một chút rào cản. Tôi có một kịch bản RẤT tương tự như mô tả tại: DialogFragment - retaining listener after screen rotationLàm cách nào để giữ chân người nghe trên hộp thoại tùy chỉnh được mở từ đoạn?
Giải pháp được đề xuất hoạt động tốt cho tác giả vì hộp thoại của anh đang được gọi từ một hoạt động. Trường hợp của tôi là chính xác, nhưng Hộp thoại Tuỳ chỉnh của tôi được gọi từ một Fragment thay vì một Activity. (Hoạt động IE-> Fragment-> Dialog)
Tôi đã triển khai cùng một giải pháp (thiết lập trình lắng nghe trong onResume từ phân đoạn gọi) nhưng nó không hoạt động trong trường hợp này.
Điều có vẻ đang xảy ra là khi màn hình được xoay, Android sẽ giết Hộp thoại và Phân đoạn. Sau đó tạo lại chúng TRONG THỨ TỰ ĐẶT HÀNG. Vì vậy, khi onCreateDialog của tôi được gọi trên hộp thoại tùy chỉnh của tôi, Fragment chứa vẫn chưa được tạo lại, do đó, nó có null cho trình nghe để thiết lập cho các nút tích cực và tiêu cực.
Có ai biết cách này không?
Tôi có thể đăng mã nếu có ai đó nghĩ rằng nó sẽ cần thiết, nhưng nó khá giống với mã trên chuỗi được liên kết.
CẬP NHẬT VỚI Mã sản phẩm:
public class RecipeDetailEditFragment extends SherlockFragment implements DialogInterface.OnClickListener {
private EditStepFragmentDialog stepDialog;
private Recipe newRecipe; //main data object implements parcelable
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
stepDialog = EditStepFragmentDialog.newInstance(newRecipe);
//I've also tried passing 'this' into the newInstance constructor and
//setting the listener there, but that doesn't work either
}
public void onResume() {
stepDialog.setListener(this);
super.onResume();
}
...
}
public class EditStepFragmentDialog extends DialogFragment {
private DialogInterface.OnClickListener ocl;
private static final String ARG_RECIPE = "recipe";
private Recipe recipe;
public EditStepFragmentDialog() {}
public static EditStepFragmentDialog newInstance(Recipe rec) { //(Recipe rec, DialogInterface.OnClickListener oc) as mentioned doesn't work.
EditStepFragmentDialog dia = new EditStepFragmentDialog();
Bundle args = new Bundle();
args.putParcelable(ARG_RECIPE, rec);
//dia.setListener(oc);
return dia;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
if (getArguments().containsKey(ARG_RECIPE)) {
recipe = (Recipe) getArguments().getParcelable(ARG_RECIPE);
}
...
adb.setPositiveButton("Done", ocl);
adb.setNegativeButton("Cancel", ocl);
...
return adb.create();
}
public void setListener(DialogInterface.OnClickListener cl) {
ocl = cl;
}
}
Bạn sẽ phải đăng mã – Atomix