-2

I have a view pager with "x" number of fragments , the first one is the "HomeFragment" : it contains 2 Drop Down List ( Spinner )

The UI of the other Fragments ( FragmentA , FragmentB ,FragmentC , ..... etc ) changes according the selected item value of those spinners

So the Question is : how to Pass this selected item value from the spinner in the " HomeFragmet " to use in other Fragments ?

Programmer
  • 31
  • 7
  • I'm not sure why this was marked as duplicate...and even more so to what is probably outdated solution. As question suggests there is way to do this more neatly now using `ViewModel`...and in particular one shared between the fragements. – John O'Reilly May 17 '18 at 14:43

1 Answers1

0

Try to this passing selected value to home fragment..

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Fragment fragment = new HomeFragment();
            Bundle bundle = new Bundle();
           bundle.putString("Key",spinner.getSelectedItem().toString());
            fragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

and In Home fragment getting value like this way..

below code call into onCreate method or onCreateView method..

 Bundle bundle = this.getArguments();
    if (bundle != null) {
        int i = bundle.getString("key", "defaulValue");
    }