How to transfer additional data from one fragment to another through activity

For example, in a list view hosted by ListActivity , when a user clicks on an item in a list, a new action is launched, and the previous activity transfers additional data to the new activity, as shown below

public class Notepadv2 extends ListActivity { ... @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent i = new Intent(this, NoteEdit.class); i.putExtra(NotesDbAdapter.KEY_ROWID, id); startActivityForResult(i, ACTIVITY_EDIT); } } 

How should it be if I use fragments? I mean, if I have one action in which 2 fragments are placed, and do operations with fragments, as shown below:

 // Create new fragment and transaction Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); 

How can I transfer additional data from one fragment to another fragment through host activity?

I know that on the developer's web page, Android has a good document on how to use the fragment, and how to deal with the activities, but there is no description of how to transfer data from one track to another ....

+6
source share
2 answers

Use

 Bundle data = new Bundle(); data.putString("name",value); Fragment fragment = new nameOfFragment(); fragment.setArguments(data); .navigateTo(fragment); 
+22
source

From the operation, you send data with the intention of:

 Bundle bundle = new Bundle(); bundle.putString("key", "value"); // set Fragmentclass Arguments Fragmentclass fragmentobj = new Fragmentclass(); fragmentobj.setArguments(bundle); 

and in the Fragment onCreateView method:

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String strtext = getArguments().getString("key"); return inflater.inflate(R.layout.fragment, container, false); } 

I hope this helps you.

+1
source

Source: https://habr.com/ru/post/907557/


All Articles