-7

I am building an android app and I am rather new to it. I was wondering if there is a way to dynamically add a button to a fragment by pressing a button on another fragment. For example, I have a fragment (A) that saves an input from a user and displays it in a listview on fragment (B) so I want to add a button into Fragment (B) for every user input.

Fragment A

Popup window when fab is clicked (B)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

0

It is unclear how it is implemented in the app. Say both fragments are displayed at the same time in the activity. In this case you can get a reference to another fragment with FragmentManager:

((MyFragment) getFragmentManager().findFragmentById(...)).addButton(myArgs)

If they are placed in different activities or if one replaces another, you need to use arguments Bundle to pass the information between the two:

SecondFragment secondFragment = new SecondFragment();
Bundle args = new Bundle;
args.putString("name", "batman");
secondFragment.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.container, secondFragment).commit();

// later in SecondFragment#onViewCreated
button.setText(getArgments.getString("name"));
nikis
  • 11,166
  • 2
  • 35
  • 45
0

Communication between fragments are possible via "interface". You pass on the data thru the activity that links the fragments. After receiving the corresponding data, Fragment B can perform certain actions and refresh the fragment to show the results.

Refer the below link for more info on the execution- passing data between fragments