How to pass data from a fragment to a dialogFragment How to pass data from a fragment to a dialogFragment android android

How to pass data from a fragment to a dialogFragment


What you need is to setArguments on the fragment as follows:

Bundle args = new Bundle();args.putString("key", "value");DialogFragment newFragment = new YourDialogFragment();  newFragment.setArguments(args);newFragment.show(getSupportFragmentManager(), "TAG");

All you have to do now, is catch those arguments in your fragment and use them...

AND IN THE DIALOG FRAGMENT YOU READ IT LIKE THIS...

Bundle mArgs = getArguments();String myValue = mArgs.getString("keyUsed to send it...");


I call a FragmentDialog inside a calsswhich exdented to ActivityFragment

//TODO 1                Followers clickedObj = (Followers)                 parent.getItemAtPosition(position);                Bundle bundle = new Bundle();                bundle.putString("name", clickedObj.getFollow_name());                bundle.putString("nick", clickedObj.getFollow_nickname());                bundle.putString("score", clickedObj.getFollow_score());                bundle.putString("title", clickedObj.getFollow_title());                FragmentManager fragmentManager = getSupportFragmentManager();                UserPopUp userPopUp = new UserPopUp();                //TODO 1                userPopUp.setArguments(bundle);                userPopUp.show(fragmentManager, "followers");

and I called it on onActivityCreated in my class which extended to DialogFragment

@Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        //Bundle Data Cekme başlangıç        Bundle mArgs = getArguments();        String userName = mArgs.getString("name");        String userNickName = mArgs.getString("nick");        String userTitle = mArgs.getString("title");        String userScore = mArgs.getString("score");        user_name.setText(userName);        nick_name.setText(userNickName);        challenge_title.setText(userTitle);        user_score.setText(userScore);        // bitiş    }

works pretty good


Two Fragments should never communicate directly.

The recommended way to communicate between fragments is to create a shared ViewModel object. Both fragments can access the ViewModel through their containing Activity. The Fragments can update data within the ViewModel and if the data is exposed using LiveData the new state will be pushed to the other fragment as long as it is observing the LiveData from the ViewModel.

If you are unable to use a shared ViewModel to communicate between your Fragments you can manually implement a communication flow using interfaces. However this ends up being more work to implement and it is not easily reusable in other Fragments.

for more information