2013-01-05 19 views
6

Có ai có thể xem nếu tôi làm đúng như sau. Tôi có một mảnh có progressdialog và tôi cần nó để làm việc trên một chuyển đổi định hướng. Tôi hiện làm như vậy:ProgressDialog (Fragment) hoạt động trên một công tắc định hướng

// I am using the compat libraries 
import android.support.v4.app.DialogFragment; 

public class ProgressDialogFragment extends DialogFragment { 

    private ProgressDialog mProgressDialog = null; 
    private int   mMax   = 100; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setStyle(DialogFragment.STYLE_NO_TITLE, 0); 
     setRetainInstance(true); 
    } 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     mProgressDialog = new ProgressDialog(getActivity()); 
     mProgressDialog.setTitle("Title"); 
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     mProgressDialog.setCancelable(true); 
     mProgressDialog.setProgress(0); 
     mProgressDialog.setMax(mMax); 
     mProgressDialog.setCanceledOnTouchOutside(false); 

     return mProgressDialog; 
    } 

    // there seems to be a bug in the compat library - if I don't do the following - the dialog is not show after an orientation switch 
    @Override 
    public void onDestroyView() { 
     if (getDialog() != null && getRetainInstance()) 
      getDialog().setDismissMessage(null); 
     super.onDestroyView(); 
    } 

    public void setMax(int arg1) { 
     mProgressDialog.setMax(arg1); 
     mMax = arg1; 
    } 

    public void setProgress(int arg1) { 
     mProgressDialog.setProgress(arg1); 
    } 
} 

Trong hoạt động của tôi, tôi tạo ProgressDialogFragment và tôi gọi show() khi tôi cần hộp thoại hiển thị. Tôi đang cố gắng hiểu tại sao trong phương thức onCreateDialog tôi không thể đơn giản trả về mProgressDialog nếu nó đã tồn tại (tôi nhận được một ngoại lệ nói rằng "requestFeature() phải được gọi trước khi thêm nội dung"). Chắc chắn một trong những ứng dụng của các mảnh là sử dụng lại tài nguyên trong những trường hợp này - tại sao tôi cần tạo một hộp thoại mới thay vì sử dụng hộp thoại đã có sẵn?

Trả lời

2

Bạn không thể đơn giản truyền hộp thoại cũ trong phương thức onCreateDialog vì nó có tham chiếu đến ngữ cảnh cũ, tức là hoạt động đang bị hủy.

Nếu bạn không tạo lại hộp thoại thì u sẽ kết thúc với rò rỉ bộ nhớ.

+0

Phương thức onCreate không được gọi trên công tắc định hướng - đoạn không bị phá hủy và sau đó được tạo lại. – Lieuwe

+0

Xin lỗi tôi có nghĩa là phương thức onCreateDialog sẽ được gọi lại. –

+0

Bạn đang cố gắng lưu tiến trình giữa các thay đổi định hướng? –