Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer some data to another Fragment?

How to transfer some data to another Fragment likewise it was done with extras for intents?

like image 885
Eugene Avatar asked Oct 16 '22 08:10

Eugene


People also ask

How can we send some data from one fragment to another?

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.

How do I send text from one fragment to another?

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.


1 Answers

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);
}
like image 522
Pikaling Avatar answered Oct 18 '22 22:10

Pikaling