How to pass a variable from Activity to Fragment and pass it back?

I am currently making an Android app and want to pass the date between activity and fragment. My activity has a button that opens a snippet: DatePickerFragment.

In my activity, I show the date that I want to change using the fragment. Therefore, I want to transfer the date to the date picker and send it back into action.

I tried many solutions, but none of them work. An easy way to pass an argument, but this cannot be done with fragments.

+124
android android-activity android-fragments
Jul 02
source share
8 answers

To pass information to a fragment , you set Arguments when it is created, and you can get this argument later using the onCreate or onCreateView methods of your fragment.

In the newInstance function of your fragment, you add the arguments that you want to send to it:

/** * Create a new instance of DetailsFragment, initialized to * show the text at 'index'. */ public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f; } 

Then, inside the onCreate or onCreateView method fragment, you can get the following arguments:

 Bundle args = getArguments(); int index = args.getInt("index", 0); 

If you want to now communicate with your fragment with your activity (send or not send data) , you need to use interfaces. How you can do this is very well explained in the guide for documenting the relationship between fragments. Since all fragments exchange data with each other through an action, in this guide you will see how you can send data from the actual fragment to its action container in order to use this data for the action or send it to another fragment contained in your action.

Documentation tutorial:

http://developer.android.com/training/basics/fragments/communicating.html

+203
Jul 02 '13 at 22:16
source share

Sending data from Activity to Fragment

Activity:

 Bundle bundle = new Bundle(); String myMessage = "Stackoverflow is cool!"; bundle.putString("message", myMessage ); FragmentClass fragInfo = new FragmentClass(); fragInfo.setArguments(bundle); transaction.replace(R.id.fragment_single, fragInfo); transaction.commit(); 

Fragment:

Reading value in fragment

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String myValue = this.getArguments().getString("message"); ... ... ... } 

But if you want to send values โ€‹โ€‹from Fragment to Activity, read jpardogo answer, you will need interfaces, additional information: Communication with other fragments

+83
Jan 13 '14 at 23:17
source share

Use the EventBus library to pass an event that can hold your variable back and forth. This is a good solution because it keeps your actions and fragments loosely connected.

https://github.com/greenrobot/EventBus

+7
Jul 02 '13 at 21:52
source share

thanks @ ฯฯƒั•ฯั” K and Terry ... it helps me a lot and works great

From Activity you send data with the intention:

 Bundle bundle = new Bundle(); bundle.putString("edttext", "From Activity"); // set Fragmentclass Arguments Fragmentclass fragobj = new Fragmentclass(); fragobj.setArguments(bundle); 

and in the Fragment onCreateView method:

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // get arguments String strtext = getArguments().getString("edttext"); return inflater.inflate(R.layout.fragment, container, false); } 

link: send activity data to fragment in Android

+7
Aug 14 '18 at 7:19
source share

Sending data from Activity to XML-related fragments

If you create a fragment in Android Studio using one of the templates, for example, File> New> Fragment> Fragment (List), then the fragment is linked via XML. The newInstance method is created in the fragment, but is never called, so it cannot be used to pass arguments.

Instead, in Activity, override the onAttachFragment method

 @Override public void onAttachFragment(Fragment fragment) { if (fragment instanceof DetailsFragment) { Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); } } 

Then read the arguments in the onCreate fragment method according to other answers

+1
Jul 25 '19 at 21:06
source share

You can simply create your fragment using the package:

 Fragment fragment = Fragment.instantiate(this, RolesTeamsListFragment.class.getName(), bundle); 
0
Apr 18 '18 at 12:43 on
source share

Do it in Kotlin style

1) Create an inline function:

 inline fun <FRAGMENT : Fragment> FRAGMENT.putArgs(argsBuilder: Bundle.() -> Unit): FRAGMENT = this.apply { arguments = Bundle().apply(argsBuilder) } 

2) Now you can use this extension in all fragments without duplicating code:

 class MyFragment: Fragment() { companion object { fun newInstance(name: String) = MyFragment().putArgs { putString("nameKey", name) } } } class MyFragment1: Fragment() { companion object { fun newInstance(boolean: Boolean) = MyFragment1().putArgs { putBoolean("booleanKey", boolean) } } } 

3) Create your fragments:

 val myFragment = MyFragment.newInstance("NAME") val myFragment1 = MyFragment1.newInstance(true) 
0
Jan 30 '19 at 14:51
source share

For all Kotlin developers:

Here is the solution Android Studio offers to send data to your fragment (= when you create an empty fragment using a file โ†’ New โ†’ Fragment โ†’ Fragment (empty) and you mark โ€œenable fragment factoryโ€ โ€).

Put this in your snippet:

 class MyFragment: Fragment { ... companion object { @JvmStatic fun newInstance(isMyBoolean: Boolean) = MyFragment().apply { arguments = Bundle().apply { putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean) } } } } 

.apply is a good technique for setting data when creating an object, or as they claim here :

Calls the specified function [block] with the value of this as the receiver and returns the value of this .

Then in your activity or fragment do:

 val fragment = MyFragment.newInstance(false) ... // transaction stuff happening here 

and read the Arguments in your snippet, such as:

 private var isMyBoolean = false override fun onAttach(context: Context?) { super.onAttach(context) arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let { isMyBoolean = it } } 

To "send" data back to your activity , simply define the function in your activity and follow these steps in your fragment:

 (activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class 

Enjoy the magic of Kotlin!

0
Sep 23 '19 at 11:03
source share



All Articles