How to use setArguments() and getArguments() methods in Fragments?
Just call getArguments()
in your Frag2
's onCreateView()
method:
public class Frag2 extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
}
EDIT:
Best practice is read and save arguments in onCreate
method. It's worse to do it in onCreateView
because onCreateView
will be called each time when fragment creates view (for example each time when fragment pops from backstack)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
}
in Frag1:
Bundle b = new Bundle();
b.putStringArray("arrayname that use to retrive in frag2",StringArrayObject);
Frag2.setArguments(b);
in Frag2:
Bundle b = getArguments();
String[] stringArray = b.getStringArray("arrayname that passed in frag1");
It's that simple.
Eg: Add data:-
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
bundle.putString("board_id", board_id);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
Eg: Get data :-
String latitude = getArguments().getString("latitude")
You have a method called getArguments()
that belongs to Fragment
class.