skip to Main Content

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.

2

Answers


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

    or use a Shared View Model.

    Login or Signup to reply.
  2. 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);
              }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search