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

Time:10-12

I have created tab layout and in one fragment I am using button to transfer data to other fragment that is on second position of tablayout. So when I will click on a button in first fragment then a text string should be sent to second fragment and should be shown in a textview in that fragment.

CodePudding user response:

Either put those data in a variable in activity and fragments can access that data from parent Activity..

or use a Shared View Model.

CodePudding user response:

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