旋转设备后从DialogFragment接收回调时,片段未附加到Activity

HBG*_*HBG 1 android android-fragments

我正在创建一个应用程序,允许用户从图库上载图像或使用设备相机拍摄照片。单击适当的按钮时,将出现一个对话框,用户可以选择“拍摄照片”或“选择图像”。一切正常,问题是当我在对话框显示在屏幕上时旋转设备,然后选择一个选项,应用程序崩溃时IllegalStateException说我的片段未连接到活动。我已经包含了用于与目标片段进行通讯的对话框:

创建DialogFragment:

public void onClick() {
    // Display a Dialog for choice between pick/ take picture
    ListDialogFragment dialogFragment = ListDialogFragment.newInstance(R.string.take_photo, R.array.add_picture_options_array);
    dialogFragment.setTargetFragment(this, 0);
    dialogFragment.show(getFragmentManager(), "Moo");
}
Run Code Online (Sandbox Code Playgroud)

DialogFragment类:

public class ListDialogFragment extends DialogFragment {

private static final String TITLE_RESOURCE_ID = "title_resource_id";
private static final String ARRAY_RESOURCE_ID = "array_resource_id";

private DialogItemSelectedListener listener;

public interface DialogItemSelectedListener {
    void onTakePhotoSelected();

    void onSelectImageSelected();
}

public ListDialogFragment() {
    // Default empty constructor
}

public static ListDialogFragment newInstance(@StringRes final int titleResourceId, @ArrayRes final int arrayResourceId) {
    ListDialogFragment dialogFragment = new ListDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(TITLE_RESOURCE_ID, titleResourceId);
    bundle.putInt(ARRAY_RESOURCE_ID, arrayResourceId);
    dialogFragment.setArguments(bundle);
    return dialogFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        listener = (DialogItemSelectedListener) getTargetFragment();
    } catch (ClassCastException e) {
        throw new ClassCastException("Calling Fragment must implement DialogItemSelectedListener");
    }
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final int title = getArguments().getInt(TITLE_RESOURCE_ID);
    final int listItems = getArguments().getInt(ARRAY_RESOURCE_ID);

    return new AlertDialog.Builder(getActivity()).setTitle(title).setItems(listItems, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case 0:
                    listener.onTakePhotoSelected();
                    break;
                case 1:
                    listener.onSelectImageSelected();
                    break;
                default:
                    dismiss();
            }
        }
    }).create();
}
Run Code Online (Sandbox Code Playgroud)

}

该片段实现,DialogItemSelectedListener并在onTakePhotoSelected()调用时尝试执行以下操作:

private void takePicture() {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Here, we make sure that an Activity to handle the Camera Intent actually exists
    if (cameraIntent.resolveActivity(context.getApplicationContext().getPackageManager()) != null) {
        // This is where the photo itself will actually go
        imageFile = null;
        try {
            imageFile = createImageFile();
        } catch (IOException ex) {
            // Could not create the file
        }

        // At this point, we can safely assume that the file was created successfully
        if (imageFile != null) {
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

活动:

public class TestActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_activity);
    attachFragment();
}

private void attachFragment() {
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, TestFragment.newInstance()).commit();
}
Run Code Online (Sandbox Code Playgroud)

}

调用时应用崩溃 startActivityForResult();

java.lang.IllegalStateException: Fragment MyTestFragment{22b2a6a0} not attached to Activity
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?这是预期的行为吗?我已经尝试过了,setRetainInstance(true);但这不起作用。

Tom*_*lec 5

这里的问题是,每次方向改变时,您都在创建一个Fragment的新实例。实际上只有其中之一与该活动相关。尝试这个

    public class TestActivity extends ActionBarActivity {

    TestFragment testFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);
        attachFragment(savedInstanceState);
    }

    private void attachFragment(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
           testFragment = TestFragment.newInstance();
           getSupportFragmentManager().beginTransaction()
           .replace(R.id.fragment_container, testFragment, "testFragment").commit();
        } else {
           testFragment = (TestFragment) getSupportFragmentManager().findFragmentByTag("testFragment");
        }
    }
Run Code Online (Sandbox Code Playgroud)