简体   繁体   中英

Passing data from spinner to TextView depending on user selection

So I have a Spinner that contains 2 possible options. But i have only one TextView in other activity where the user selection will show.

The problem is, how do I set that in second activity? Tried numerous times with various if - statements, nothing worked.

Here's the code of my spinner

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0){

                            intent.putExtra("ciljJePovecanjeTezine", cilj.getSelectedItem().toString());

                        } else if (position == 1){
                            intent.putExtra("ciljJeMrsavljenje", cilj.getSelectedItem().toString());

                        }
                    }

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

                    }
                });

and here's the second activity in which I want text to appear

String prehrana = intent.getStringExtra("ciljJePovecanjeTezine");
        String prehrana2 = intent.getStringExtra("ciljJeMrsavljenje");

        ciljPrehranaRezultat = (TextView) findViewById(R.id.textViewPrehranaCiljRezultat);

        ciljPrehranaRezultat.setText(prehrana);
        ciljPrehranaRezultat.setText(prehrana2);

Now how do I set that if user selects option one, option one shows in TextView and if user selects option two, option two appears?

Thanks!!

You should use a global String variable to save the spinner value and then send that to the other activity on press of a button (or whatever you are using to change activity). For example:

String spinnerValue;

public void onCreate(...){
...
spinnerValue = cilj.getSelectedItem().toString()
...
}

public void onItemSelected(...){
     spinnerValue = cilj.getSelectedItem().toString();
}


Intent intent = new Intent(THIS_ACTIVITY,OTHER_ACTIVITY.CLASS);
intent.putExtra("spinnerValue",spinnerValue);
startActivity...

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