有几篇关于类似问题的文章,但我只是找不到正确的答案,我希望有人能帮助我。

情况:
我有一个包含多个片段的MainActivity。在一个片段中,我以意图开始一个CameraActivity。用户拍摄完照片后,CameraActivityfinish()关闭,我们返回上一个Fragment。

目标:
我给Picture指定了一个名称,并希望将此名称从CameraActivity传递给Fragment。

问题:
即使我在CameraActivity中调用finish(),并且屏幕返回到前一个Fragment,也永远不会调用方法onSaveInstanceState(Bundle outstate)。这是为什么?

否则我该如何解决这个问题?

这是我的代码:

public class CameraActivity extends Activity {
    // more code here

    String imageFileName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // some methods here
        finish(); // finish the current Activity and get back to previous Fragment
    }

    // more code here

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.d(TAG_LOG, "onSaveInstanceState() called"); // is never called!
        outState.putString("imageFileName", imageFileName);
        super.onSaveInstanceState(outState);
    }
}


在片段中,我这样做:

public class MapFragment extends Fragment implements View.OnClickListener {

    // more code here

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        // some methods here

        if (savedInstanceState != null) {
            String imageFileName = getArguments().getString("imageFileName");
            Log.d(TAG_LOG, "image filename: " + imageFileName);
        }

        return view;
    }

    // more code here
}


任何帮助深表感谢!

最佳答案

您应该看看startActivityForResults。这是一个简短的示例(尚未尝试过,但您会明白的):

分段

Intent intent = new Intent(MainActivity.this,CameraActivity.class);
getActivity().startActivityForResult(intent,RESULT_PIC_TAKEN); // you may start an activity from another activity, not a fragment


CameraActivity

Intent results = new Intent();
results.putExtra("com;yourpackage.PIC_NAME", picName);
setResult(CameraActivity.RESULT_OK,results);
finish();


返回MainActivity(因为您调用了getActivity()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == RESULT_PIC_TAKEN) {
        if(resultCode == Activity.RESULT_OK){
            Bundle results = data.getExtras();
            String picName = results.getString("com.yourpackage.PIC_NAME");
            // code, and send what you want to the fragment
        }
    }
}


希望对你有帮助!

07-24 16:35