First Method
eg:-
Code: Select all
Bundle bundle = new Bundle();
bundle.putString("Key", "StringValue");
NewFragment fragobj = new NewFragment();
fragobj.setArguments(bundle);
Then in Fragment we can take the data as
Fragment onCreateView method:
Code: Select all
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
String strtext = getArguments().getString("Key");
return inflater.inflate(R.layout.fragment, container, false);
}
Second Method :
you can create any public function in MainActivity.java which is the parent Activity of the fragment
eg:-
Code: Select all
public void String getData()
{
return "Data from Activity";
}
Then in Fragment, you can Cast the MainActitivy to an object like this
Code: Select all
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
MainActivity activity = (MainActivity)getActivity();
String Data = activity.getData();
return inflater.inflate(R.layout.fragment, container, false);
}
Third Method For Sending Complex Data
for complex objects you need to implement Serializable. For example, for the simple object:
Code: Select all
public class MyClass implements Serializable {
private static final long serialVersionUID = -2163051469151804394L;
private int id;
private String created;
}
In you FromFragment:
Code: Select all
Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
.addToBackStack(TAG_TO_FRAGMENT).commit();
in your ToFragment:
Code: Select all
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
MyClass myClass = (MyClass) args
.getSerializable(TAG_MY_CLASS);
...
}