【问题标题】:Android coming from camera loses fragment view来自相机的 Android 丢失片段视图
【发布时间】:2017-09-01 11:44:19
【问题描述】:

我已经实现了一个包含一些步骤的公式。每一步都在一个新的Fragment 中使用FrameLayout。

在最后一步 (FRAGMENT A) 中有一个Button。当单击此Button 时,将启动一个新的Fragment (FRAGMENT B) 并启动相机Intent。

有时在拍摄照片并关闭相机后,会显示FRAGMENT A 而不是FRAGMENT B。发生这种情况时,UI 元素被冻结,任何字段都可以点击,继续使用应用程序的唯一方法是关闭Form 并重新开始该过程。

我认为这是一个OOM 错误,所以Activity 被杀死/恢复并且最后一个状态没有正确存储。

我试过检查,但没有调用方法onRestoreInstanceState()。 FRAGMENT B 中的方法也会在相机关闭后调用,无论是否显示。这是我打开FRAGMENT B和摄像头的代码:

基础片段

private void setCurrentFragment(int pos, boolean animate) {
   showFragment(buildFragment(mCurrentPage), animate, animationFromRight);
   ....
}

private Fragment buildFragment(int pos) {
    switch (mHasFamilyManager ? pos : pos + 1) {
        ............
        case 3:
            mCurrentFragment = PhotoVerificationFragment.newInstance();
            if (mState.getAttachments().isEmpty()) {
                switch (mState.getPictureSelector()) {
                    .....
                    case CAMERA:
                        onAddCameraPictureClicked();
                        break;
                }
             .....

    return mCurrentFragment;
}

private void showFragment(final Fragment fragment, boolean animate,
        final boolean animationFromRight) {
    if (fragment != null) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (animate) {
            if (animationFromRight) {
                transaction.setCustomAnimations(R.anim.activity_slide_in_right,
                        R.anim.activity_slide_out_left);
            } else {
                transaction.setCustomAnimations(R.anim.activity_slide_in_left,
                        R.anim.activity_slide_out_right);
            }
        }
        transaction.addToBackStack(null);
        transaction.replace(R.id.container, fragment);
        transaction.commit();
    }
}

MainActivity

public void onAddCameraPictureClicked() {
    startActivityForResult(takePictureIntent, requestCode);
    .....
}

有人有想法吗?提前致谢!

【问题讨论】:

    标签: android android-fragments view fragmenttransaction


    【解决方案1】:

    请试试这个:

    transaction.add(R.id.container, fragment);
    transaction.disallowAddToBackStack();
    transaction.commit();
    

    通过使用replace,您正在替换彼此顶部的片段,因此它不会删除前一个片段或在当前片段下方添加新片段。

    使用add 可以确保它始终位于顶部。

    disallowAddToBackStack 将确保您没有在堆栈中持有任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多