我倾向于做的事情,我相信这也是 Google 打算让开发人员做的事情,仍然是从 Intent 中获取额外的 Activity,然后通过实例化它们将任何额外的数据传递给片段有论据。
实际上,Android 开发博客上的 an example 说明了这个概念,您也会在几个 API 演示中看到这一点。尽管此特定示例是针对 API 3.0+ 片段给出的,但在使用支持库中的 FragmentActivity 和 Fragment 时也适用相同的流程。
您首先像往常一样在 Activity 中检索 Intent Extras,并将它们作为参数传递给片段:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
与直接调用构造函数不同,使用静态方法为您插入参数到片段中可能更容易。这种方法在examples given by Google 中通常称为newInstance。 DetailsFragment中其实有一个newInstance方法,所以我不确定为什么上面的sn-p中没有用到...
无论如何,在创建片段时作为参数提供的所有额外内容都可以通过调用getArguments() 获得。由于这会返回一个Bundle,因此它的用法类似于Activity 中的额外内容。
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}