在 Android 片段中的何处/如何获得意图()?

在活动中,我经常这样做:

活动一:

Intent i = new Intent(getApplicationContext(), MyFragmentActivity.class);
i.putExtra("name", items.get(arg2));
i.putExtra("category", Category);
startActivity(i);

活动二:

Item = getIntent().getExtras().getString("name");

如何使用片段实现这一点? 我也使用了兼容性库 v4。

它是放在片段活动中? 还是放在实际的片段中? 它放在哪个方法里? onCreate? onCreateView? 另一个?

我能看一下示例代码吗?

编辑: 值得注意的是,我试图保持活动1作为一个活动(或者实际上是 ListActivity,当我点击它时,我正在传递列表的意图) ,然后传递给一组选项卡片段(通过片段活动) ,我需要任何一个选项卡才能获得额外的内容。(我希望这是可能的?)

149124 次浏览

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

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();
}
}
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an 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)


}

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.