How are parameters passed in Android Fragments?
In Android, parameters can be passed to a Fragment using a Bundle. The specific steps are as follows:
- Create a Bundle object and use the put method to pass parameters. For example, if you want to pass a string parameter, you can use the putString method:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
- Create an instance of Fragment and call the setArguments method to pass a Bundle object.
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
- In a Fragment, you can retrieve a Bundle object using the getArguments method and access the passed parameters using methods like getString.
Bundle args = getArguments();
if (args != null) {
String value = args.getString("key");
}
In this way, it is possible to pass parameters to a Fragment when creating an instance of it in an Activity.