Jieun Chon
Jieun Chon

Reputation: 139

Android spinner and change text depends on the Item selection

I am an android noob, and I am trying to make a spinner that and want to change the another text depends on the spinner item selection.

For example, if I choose juice, I need to change the text to "gallons." etc.

This is my code:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit);

    Button saveButton = (Button) findViewById(R.id.save_button);
     Spinner foodSpinner = (Spinner) findViewById(R.id.foodSpinner);
     String foodChoice = foodSpinner.getSelectedItem().toString();
     TextView unit = (TextView) findViewById(R.id.units);

     if(foodChoice.equals("Egg"))
     {
     unit.setText("Dozen");
     }
     else if(foodChoice.equals("Juice"))
     {
     unit.setText("gallons");
     }
     else if(foodChoice.equals("Carrot"))
     {
     unit.setText("bunch");
     }
     else if(foodChoice.equals("Chocolate"))
     {
     unit.setText("bars");
     }
     else if(foodChoice.equals("Bread"))
     {
     unit.setText("loaf");
     }

    saveButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(EditActivity.this,
                    MainActivity.class);
            startActivity(intent);
        }
    });
}

But the text changed to "Dozens" first time, and then it is not changed when I select other Items from the spinner.

Upvotes: 2

Views: 2519

Answers (3)

Fahim
Fahim

Reputation: 12368

Add on item selected listener like as

    sp.setOnItemSelectedListener(new OnItemSelectedListener(){
  public void onItemSelected(AdapterView<?> arg0, View arg1,   int arg2, long arg3){

Toast.makeText(getBaseContext(), sp.getSelectedItem().toString(),

Toast.LENGTH_LONG).show();                            }                     
   }

Upvotes: 0

Nick H
Nick H

Reputation: 8992

I dont see an onItemSelectedListener anywhere. Make sure you set one on the spinner. foodSpinner.setOnItemSelectedListener(new onItemSelectedListener...)

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

Add setOnItemSelectedListener to Spinner to change TextView text according to Spinner selection:

foodSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub

            String selItem = foodSpinner.getItemAtPosition(arg2).toString();

            if(selItem.equals("Juice"))
             {
               unit.setText("gallons");
             }....
        }
    });

Upvotes: 3

Related Questions