Passing a Spinner value from one fragment to another












0















I need to get the value of the spinner set in the first fragment and pass the value along to fragment 2. At the moment I'm just trying to set one text field in fragment 2 to the spinner's value, but later on I'll need to somehow have the fragment 1 spinner value match a unit like meters, and then for fragment 2 to be able to take that unit and a user input to then convert it into a second chosen user input.



In fragment 2 I have just typed out some 'bad' psuedo code to showcase what I'm trying to do:



Main Activity



public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);



Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page2));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {}
});



}


Fragment 1



public class Page1Fragment extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {

View view = inflater.inflate(R.layout.page1_fragment, container, false);


Spinner spinner = (Spinner) view.findViewById(R.id.spinner);

// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);



return view;

}


Fragment 2



public class Page2Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.page2_fragment, container, false);
fragment1Spinner = Page1Fragment.getSpinnerValue

TextView text = (TextView) view.findViewById(R.id.textView2);
text.setText(fragment1Spinner);

return view;

}
}









share|improve this question





























    0















    I need to get the value of the spinner set in the first fragment and pass the value along to fragment 2. At the moment I'm just trying to set one text field in fragment 2 to the spinner's value, but later on I'll need to somehow have the fragment 1 spinner value match a unit like meters, and then for fragment 2 to be able to take that unit and a user input to then convert it into a second chosen user input.



    In fragment 2 I have just typed out some 'bad' psuedo code to showcase what I'm trying to do:



    Main Activity



    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page1));
    tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page2));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),
    tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new
    TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());
    }
    @Override
    public void onTabUnselected(TabLayout.Tab tab) {}
    @Override
    public void onTabReselected(TabLayout.Tab tab) {}
    });



    }


    Fragment 1



    public class Page1Fragment extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
    savedInstanceState) {

    View view = inflater.inflate(R.layout.page1_fragment, container, false);


    Spinner spinner = (Spinner) view.findViewById(R.id.spinner);

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);



    return view;

    }


    Fragment 2



    public class Page2Fragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
    savedInstanceState) {
    View view = inflater.inflate(R.layout.page2_fragment, container, false);
    fragment1Spinner = Page1Fragment.getSpinnerValue

    TextView text = (TextView) view.findViewById(R.id.textView2);
    text.setText(fragment1Spinner);

    return view;

    }
    }









    share|improve this question



























      0












      0








      0








      I need to get the value of the spinner set in the first fragment and pass the value along to fragment 2. At the moment I'm just trying to set one text field in fragment 2 to the spinner's value, but later on I'll need to somehow have the fragment 1 spinner value match a unit like meters, and then for fragment 2 to be able to take that unit and a user input to then convert it into a second chosen user input.



      In fragment 2 I have just typed out some 'bad' psuedo code to showcase what I'm trying to do:



      Main Activity



      public class MainActivity extends AppCompatActivity {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);



      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);

      TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
      tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page1));
      tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page2));
      tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
      final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
      final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),
      tabLayout.getTabCount());
      viewPager.setAdapter(adapter);
      viewPager.addOnPageChangeListener(new
      TabLayout.TabLayoutOnPageChangeListener(tabLayout));
      tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
      @Override
      public void onTabSelected(TabLayout.Tab tab) {
      viewPager.setCurrentItem(tab.getPosition());
      }
      @Override
      public void onTabUnselected(TabLayout.Tab tab) {}
      @Override
      public void onTabReselected(TabLayout.Tab tab) {}
      });



      }


      Fragment 1



      public class Page1Fragment extends Fragment {


      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
      savedInstanceState) {

      View view = inflater.inflate(R.layout.page1_fragment, container, false);


      Spinner spinner = (Spinner) view.findViewById(R.id.spinner);

      // Create an ArrayAdapter using the string array and a default spinner layout
      ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
      // Specify the layout to use when the list of choices appears
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      // Apply the adapter to the spinner
      spinner.setAdapter(adapter);



      return view;

      }


      Fragment 2



      public class Page2Fragment extends Fragment {
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
      savedInstanceState) {
      View view = inflater.inflate(R.layout.page2_fragment, container, false);
      fragment1Spinner = Page1Fragment.getSpinnerValue

      TextView text = (TextView) view.findViewById(R.id.textView2);
      text.setText(fragment1Spinner);

      return view;

      }
      }









      share|improve this question
















      I need to get the value of the spinner set in the first fragment and pass the value along to fragment 2. At the moment I'm just trying to set one text field in fragment 2 to the spinner's value, but later on I'll need to somehow have the fragment 1 spinner value match a unit like meters, and then for fragment 2 to be able to take that unit and a user input to then convert it into a second chosen user input.



      In fragment 2 I have just typed out some 'bad' psuedo code to showcase what I'm trying to do:



      Main Activity



      public class MainActivity extends AppCompatActivity {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);



      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);

      TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
      tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page1));
      tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page2));
      tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
      final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
      final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),
      tabLayout.getTabCount());
      viewPager.setAdapter(adapter);
      viewPager.addOnPageChangeListener(new
      TabLayout.TabLayoutOnPageChangeListener(tabLayout));
      tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
      @Override
      public void onTabSelected(TabLayout.Tab tab) {
      viewPager.setCurrentItem(tab.getPosition());
      }
      @Override
      public void onTabUnselected(TabLayout.Tab tab) {}
      @Override
      public void onTabReselected(TabLayout.Tab tab) {}
      });



      }


      Fragment 1



      public class Page1Fragment extends Fragment {


      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
      savedInstanceState) {

      View view = inflater.inflate(R.layout.page1_fragment, container, false);


      Spinner spinner = (Spinner) view.findViewById(R.id.spinner);

      // Create an ArrayAdapter using the string array and a default spinner layout
      ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
      // Specify the layout to use when the list of choices appears
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      // Apply the adapter to the spinner
      spinner.setAdapter(adapter);



      return view;

      }


      Fragment 2



      public class Page2Fragment extends Fragment {
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
      savedInstanceState) {
      View view = inflater.inflate(R.layout.page2_fragment, container, false);
      fragment1Spinner = Page1Fragment.getSpinnerValue

      TextView text = (TextView) view.findViewById(R.id.textView2);
      text.setText(fragment1Spinner);

      return view;

      }
      }






      java android android-fragments






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 4:52









      Ishaan Javali

      1,3643821




      1,3643821










      asked Nov 23 '18 at 2:49







      user9730036































          1 Answer
          1






          active

          oldest

          votes


















          0














          Add an onItemSelectedListener on your spinner to get the value selected in spinner. Store it in an variable and use setArguments and get arguments method of fragment to set and get the value..



          Example:



          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();
          }

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

          }
          });


          For setting the arguments to your fragment...considering you have a method in your fragment names newInstance. set this when navigating to second fragment.



          Bundle bundle = new Bundle();
          bundle.putString("selectedSpinnerItemKey", selectedSpinnerItemValue);

          Fragment fragment = YourFragment.newInstance();
          fragment.setArguments(bundle);

          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          transaction.replace(R.id.fragmentContent, fragment);
          transaction.commit();


          Now getting the arguments in second fragment.



          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
          {
          if (getArguments() != null)
          {
          String itemFromFirstFragment = getArguments().getString("selectedSpinnerItemKey");
          }
          }





          share|improve this answer


























          • I don't understand where the second method is meant to be placed

            – user9730036
            Nov 23 '18 at 14:51











          • I've edit the answer please check and hope it solves your issue.

            – Amit Jangid
            Nov 24 '18 at 3:55











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440097%2fpassing-a-spinner-value-from-one-fragment-to-another%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown
























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Add an onItemSelectedListener on your spinner to get the value selected in spinner. Store it in an variable and use setArguments and get arguments method of fragment to set and get the value..



          Example:



          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();
          }

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

          }
          });


          For setting the arguments to your fragment...considering you have a method in your fragment names newInstance. set this when navigating to second fragment.



          Bundle bundle = new Bundle();
          bundle.putString("selectedSpinnerItemKey", selectedSpinnerItemValue);

          Fragment fragment = YourFragment.newInstance();
          fragment.setArguments(bundle);

          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          transaction.replace(R.id.fragmentContent, fragment);
          transaction.commit();


          Now getting the arguments in second fragment.



          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
          {
          if (getArguments() != null)
          {
          String itemFromFirstFragment = getArguments().getString("selectedSpinnerItemKey");
          }
          }





          share|improve this answer


























          • I don't understand where the second method is meant to be placed

            – user9730036
            Nov 23 '18 at 14:51











          • I've edit the answer please check and hope it solves your issue.

            – Amit Jangid
            Nov 24 '18 at 3:55
















          0














          Add an onItemSelectedListener on your spinner to get the value selected in spinner. Store it in an variable and use setArguments and get arguments method of fragment to set and get the value..



          Example:



          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();
          }

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

          }
          });


          For setting the arguments to your fragment...considering you have a method in your fragment names newInstance. set this when navigating to second fragment.



          Bundle bundle = new Bundle();
          bundle.putString("selectedSpinnerItemKey", selectedSpinnerItemValue);

          Fragment fragment = YourFragment.newInstance();
          fragment.setArguments(bundle);

          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          transaction.replace(R.id.fragmentContent, fragment);
          transaction.commit();


          Now getting the arguments in second fragment.



          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
          {
          if (getArguments() != null)
          {
          String itemFromFirstFragment = getArguments().getString("selectedSpinnerItemKey");
          }
          }





          share|improve this answer


























          • I don't understand where the second method is meant to be placed

            – user9730036
            Nov 23 '18 at 14:51











          • I've edit the answer please check and hope it solves your issue.

            – Amit Jangid
            Nov 24 '18 at 3:55














          0












          0








          0







          Add an onItemSelectedListener on your spinner to get the value selected in spinner. Store it in an variable and use setArguments and get arguments method of fragment to set and get the value..



          Example:



          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();
          }

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

          }
          });


          For setting the arguments to your fragment...considering you have a method in your fragment names newInstance. set this when navigating to second fragment.



          Bundle bundle = new Bundle();
          bundle.putString("selectedSpinnerItemKey", selectedSpinnerItemValue);

          Fragment fragment = YourFragment.newInstance();
          fragment.setArguments(bundle);

          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          transaction.replace(R.id.fragmentContent, fragment);
          transaction.commit();


          Now getting the arguments in second fragment.



          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
          {
          if (getArguments() != null)
          {
          String itemFromFirstFragment = getArguments().getString("selectedSpinnerItemKey");
          }
          }





          share|improve this answer















          Add an onItemSelectedListener on your spinner to get the value selected in spinner. Store it in an variable and use setArguments and get arguments method of fragment to set and get the value..



          Example:



          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();
          }

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

          }
          });


          For setting the arguments to your fragment...considering you have a method in your fragment names newInstance. set this when navigating to second fragment.



          Bundle bundle = new Bundle();
          bundle.putString("selectedSpinnerItemKey", selectedSpinnerItemValue);

          Fragment fragment = YourFragment.newInstance();
          fragment.setArguments(bundle);

          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          transaction.replace(R.id.fragmentContent, fragment);
          transaction.commit();


          Now getting the arguments in second fragment.



          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
          {
          if (getArguments() != null)
          {
          String itemFromFirstFragment = getArguments().getString("selectedSpinnerItemKey");
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '18 at 3:54

























          answered Nov 23 '18 at 4:01









          Amit JangidAmit Jangid

          1,2731917




          1,2731917













          • I don't understand where the second method is meant to be placed

            – user9730036
            Nov 23 '18 at 14:51











          • I've edit the answer please check and hope it solves your issue.

            – Amit Jangid
            Nov 24 '18 at 3:55



















          • I don't understand where the second method is meant to be placed

            – user9730036
            Nov 23 '18 at 14:51











          • I've edit the answer please check and hope it solves your issue.

            – Amit Jangid
            Nov 24 '18 at 3:55

















          I don't understand where the second method is meant to be placed

          – user9730036
          Nov 23 '18 at 14:51





          I don't understand where the second method is meant to be placed

          – user9730036
          Nov 23 '18 at 14:51













          I've edit the answer please check and hope it solves your issue.

          – Amit Jangid
          Nov 24 '18 at 3:55





          I've edit the answer please check and hope it solves your issue.

          – Amit Jangid
          Nov 24 '18 at 3:55




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440097%2fpassing-a-spinner-value-from-one-fragment-to-another%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          If I really need a card on my start hand, how many mulligans make sense? [duplicate]

          Alcedinidae

          Can an atomic nucleus contain both particles and antiparticles? [duplicate]