2

I have an activity where the user press a button and then is send to a fragment, but I wish to pass an extra for the use of the fragment:

activity A(where is the button):

public OnClickListener publish = new OnClickListener(){

       @Override
       public void onClick(View v) {


           Intent intent = new Intent(v.getContext(),ActivityB.class);
           intent.putExtra("friendIdRowID", rowID);
           startActivity(intent);


       }
   };

Activity B is loading the fragment(where I wish to retrieve the extra "friendIdRowID"), the fragment:

 @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.activity_main2, container, false);

            Bundle extras = getActivity().getIntent().getExtras();

        if (extras != null)
        {

            String myString = extras.getString("friendIdRowID");
}
        }

But it is not working, what can I do to pass and retrieve the extra? thanks.

4

1 回答 1

8

您需要使用 的setArguments()方法Fragment将信息传递到您的片段中。在创建片段的活动中,执行以下操作:

YourFragment f = new YourFragment();
Bundle args = new Bundle();
args.putString("friendIDRowID", getIntent().getExtras().getString("friendIDRowID"));
f.setArguments(args);
transaction.add(R.id.fragment_container, f, "tag").commit();

然后,覆盖onCreate()您的方法Fragment并执行以下操作:

Bundle args = getArguments();
String myString = args.getString("friendIdRowID");

就像 Activity 的附加功能一样,您可以根据需要向参数包中添加任意数量的内容。希望这可以帮助!

于 2013-11-02T22:19:44.800 回答