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.
Asked
Active
Viewed 66 times
-7
-
What you need is [basic-communication-between-two-fragments](https://stackoverflow.com/questions/13700798/basic-communication-between-two-fragments). – ADM Feb 07 '18 at 11:01
-
plz post pictures of the scenerio – Nirmal Prajapat Feb 07 '18 at 11:18
2 Answers
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

Ashok Mani
- 1
- 1