简体   繁体   中英

Spinner only show first input in output

I made a spinner where its possible to select 1 sport and it gives you the calories per hour. I did this as follows:

package com.test.moneyconverter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class sport extends Activity  {

  Button mBtnCalculate;

  String Voetbal        =   "190";
  String Zwemmen        =   "240";
  String Fietsen        =   "480";
  String Hardlopen  =   "480";
  String Wandelen   =   "150";

  String Selected = spinner.getSelectedItem().toString();

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sport);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    mBtnCalculate = (Button) findViewById(R.id.btnCalculate);

    ArrayAdapter myAdapter = new ArrayAdapter(this,
        android.R.layout.simple_spinner_item,
        new String[]{"Voetbal","Zwemmen","Fietsen","Hardlopen","Wandelen"});
    Spinner sport = (Spinner) findViewById(R.id.spinner);
    sport.setAdapter(myAdapter);
  }

  public void calculateTo(View view){
    if (view == mBtnCalculate){
      float calorien = Float.valueOf(Selected.toString());
      Toast.makeText(this, "je verbrand "  + calorien , Toast.LENGTH_LONG).show();   
    }        
  }
}   

It only show the first output, always Voetbal. I think it doesn't work because it doesn't select the output?

I'm not an Android developer, so I'm probably missing some other problems with your code, however you appear to have made the mistake of thinking the Selected variable will update whenever the spinner does:

String Selected = spinner.getSelectedItem().toString();

This variable will never change its value. Instead you need to call spinner.getSelectedItem().toString() when the user presses the button to get the current value.


This part of your code also looks strange:

float calorien = Float.valueOf(Selected.toString());

Based on your description of your task, I would expect your spinner to return text values, such as "Voetbal" etc. Those are not float values, so you can't convert them in the manner that you do. Perhaps instead you need to define a map structure that maps strings such as "Voetbal" to float values:

Map<String, Float> map = new HashMap<String, Float>() {{
  put("Voetbal", 190f);
  // etc.
}};

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