How to transfer some data to another Fragment
likewise it was done with extras
for intents
?
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.
So to share a string between fragments you can declare a static String in Activity. Access that string from Fragment A to set the value and Get the string value in fragment B. 2. Both fragments are hosted by different Activities- Then you can use putExtra to pass a string from Fragment A of Activity A to Activity B.
Use a Bundle
. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment
, retrieve the data (e.g. in onCreate()
method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With