【发布时间】:2018-01-07 18:31:36
【问题描述】:
我正在尝试将数据从我的 Main Activity 传递给我的 Camera Activity,再传递给我的 Camera Fragment,然后再传回我的 Main Activity。我希望用户能够保存他们在 Main Activity 上输入的信息,以便在他们使用完相机后保留下来。
在我的 Main Activity 上,我将以下内容作为 Intent Extras 传递给 Camera Activity:
(注意:这可行)
Intent cameraIntent = new Intent(MainActivity.this, CameraActivity.class);
cameraIntent.putExtra("description" , editTextDescription.getText().toString());
cameraIntent.putExtra("category" , editTextCategory.getText().toString());
cameraIntent.putExtra("notes" , editTextNotes.getText().toString());
MainActivity.this.startActivity(cameraIntent);
然后,我将成功接收 Camera Activity 上的附加内容,并将它们打包传递给我的 Camera Fragment:
(注意:这可行)
Intent intent = getIntent();
if (intent.getExtras() != null) {
description = intent.getExtras().getString("description");
category = intent.getExtras().getString("category");
notes = intent.getExtras().getString("notes");
}
if (null == savedInstanceState) {
CameraFragment cameraFragment = new CameraFragment();
Bundle bundle = new Bundle();
bundle.putString("description", description);
bundle.putString("category", category);
bundle.putString("notes", notes);
cameraFragment.setArguments(bundle);
Log.v(TAG, "Here is the bundle: " + bundle.toString());
getFragmentManager().beginTransaction()
.replace(R.id.container, cameraFragment.newInstance())
.add(cameraFragment, bundle.toString())
.commit();
}
在我的 Camera Fragment 中,我收到了 onCreateView 中的捆绑包,如下所示:
(注意:这可行)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments() != null) {
description = getArguments().getString("description");
category = getArguments().getString("category");
notes = getArguments().getString("notes");
Log.v(TAG, "Here are your arguments from the camera activity: " + description + " " + category + " " + notes);
}
else {
Log.v(TAG, "Your arguments are null");
}
return inflater.inflate(R.layout.fragment_camera, container, false);
}
所有这些交易都在正确执行,到目前为止,我已正确收到所有信息。我现在的目标是获取信息,并将其传递回 Main Activity。
问题**
case R.id.doneButton: {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("description", description);
intent.putExtra("category", category);
intent.putExtra("notes", notes);
Log.v(TAG, "Here are the extras going back to the Main Activity " + description + " " + category + " " + notes);
startActivity(intent);
break;
}
但是,我无法获取我在 Fragment 中收到的信息,并在其他地方使用变量。我试图尝试在 onCreateView 以外的方法中获取参数,然后在将附加内容传递回 Main Activity 之前使用该方法。我也尝试在我的 onClick 开关、case 方法中获取参数,但是,当我尝试将数据发送回我的 Main Activity 时,它总是返回 null,因为它没有采用它在参数中收到的内容,而是使用我之前声明的字符串。
private String description;
private String category;
private String notes;
有没有办法获取我在 Camera Fragment 的参数中收到的数据,并在 onCreateView 方法之外使用它们,然后将它们发送回我的主要活动?
【问题讨论】:
-
那么您是说您的 doneButton 开关盒中的描述、类别和注释为空?
标签: java android arguments fragment bundle