简体   繁体   中英

Passing spinner value from fragment to activity

I'm trying to send the value of the spinner from the fragment to the Main activity, trying to use intent to do so, but it's not working really. I am using toast in the main activity to check if the value is passing but it isn't

Any help?

Fragment Code:

  View rootView = inflater.inflate(R.layout.fragment_language, container, false);
    Spinner spinner = (Spinner) rootView.findViewById(R.id.language_Spinner);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            // this line will get you the selected item of the spinner
            String selectedValue = parent.getItemAtPosition(position).toString();
            Intent i = new Intent(getActivity(), MainActivity.class);
            Intent i1 = new Intent(getActivity(), PetsActivity.class);
            i.putExtra("languageValue", selectedValue);
            i1.putExtra("languageValue", selectedValue);

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent)
        {
        }
    });
    return rootView;

}

Main Activity

String languageChoice = getIntent().getStringExtra("languageValue");

    Toast.makeText(this, languageChoice, Toast.LENGTH_SHORT).show();

But obviously it's not working.

How can I fix this?

If this fragment is a part of that activity, then you don't need to have an intent

you can create a method in your activity assume you name it getSpinnerValue(String value) . Then in your fragment use getActivity() or requireActivity() , cast it to your activity class, and call getSpinnerValue(value)

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        // this line will get you the selected item of the spinner
        String selectedValue = parent.getItemAtPosition(position).toString();
        ((MainActivity) getActivity()).getSpinnerValue(selectedValue);

        // ... reset of code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM