How to Send Data from One Fragment to Another Fragment

How to send data from one Fragment to another Fragment?

Use Bundle to send String:

//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

In onCreateView of the new Fragment:

//Retrieve the value
String value = getArguments().getString("YourKey");

How to transfer data from one Fragment to another?

To pass data between two fragments with jetpack navigation you have to use Safe Args

pass an argument section like

 <fragment android:id="@+id/myFragment" >
<argument
android:name="myArg"
app:argType="integer"
android:defaultValue="0" />
</fragment>

add classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version" in top level gradle file

and add the plugin apply plugin: "androidx.navigation.safeargs.kotlin"
now send the value like so

override fun onClick(v: View) {
val amountTv: EditText = view!!.findViewById(R.id.editTextAmount)
val amount = amountTv.text.toString().toInt()
val action = SpecifyAmountFragmentDirections.confirmationAction(amount)
v.findNavController().navigate(action)
}

and receive it as

val args: ConfirmationFragmentArgs by navArgs()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val tv: TextView = view.findViewById(R.id.textViewAmount)
val amount = args.amount
tv.text = amount.toString()
}

However safeargs works only for primitive types so you have to deconstruct and reconstruct if you're trying to pass Objects

how to send data from one fragment to an other fragment using interface in tablayout

If you are transferring data like int,long,String etc. Then you can wrap your data in Bundle while creating the second Fragment and get all data in the second Fragment in its onCreate() method using getArguments() method.

In your first fragment in the onClick(View view) method-

     onClick(View view){ 

YourSecondFragment secondFragment=new YourSecondFragment();
Bundle args=new Bundle();
args.putString("create a key for your string ",your string value);
secondFragment.setArguments(args);

//.. and rest code of creating fragment transaction and commit.

And then in onCreate(Bundle savedInstanceState) method of the YourSecondFragment

        if(getArguments()!=null)
{

your_text_variable= getArguments().getString("the same key that you put in first fragment",null);

}

Finally in the onCreateView() method of secondFragment-

      if(your_text_variable!=null)
{
yourTextView.setText(your_text_variable);
}


Related Topics



Leave a reply



Submit