将微调器值与数组值相乘

时间:2016-03-01 10:57:30

标签: java android arrays spinner

这是我的代码,我想将spinner的值乘以数组值。

数组从我的另一个名为Constant的java类获取其值,并且该类具有数组food calories

protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.items_details);
        Spinner mspin=(Spinner) findViewById(R.id.spinner1);

        Integer[] items = new Integer[]{1,2,3,4};
        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
        mspin.setAdapter(adapter);

        TextView name_select=(TextView)findViewById(R.id.SelectedName);
                name_select.setText(constant.food_items[constant.SelectedIndex]);
        imageView =  (ImageView) findViewById(R.id.imagedetail);
        UpdateImage(constant.food_items[constant.SelectedIndex]);

        TextView calories=(TextView)findViewById(R.id.calories111);
                calories.setText(constant.food_calories[constant.index]+"");

        int multiple=0;

        {

             try {multiple= mspin.getSelectedItemPosition()*       constant.food_calories[constant.index];

          TextView tot_calories=(TextView)findViewById(R.id.caloriestotal);
          tot_calories.setText(multiple+"");}

          catch(NumberFormatException nfe) {
              Log.e("Error", "Failed to multiply invalid non-numbers");
                   }

常量类代码

public static final Integer[] food_calories=new Integer[]{74
};
    public static int index = 0;

}

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码解决此问题:

for loops

更新了我的答案!因为现在我已经自我测试了它是完整的解决方案。

答案 1 :(得分:0)

您需要将用于设置multiple变量值的代码放在微调器mspin的侦听器中,以便每次更改微调器时都会调用它。在onCreate方法

中添加以下代码
        mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            //Your code to set multiple's value and calculate total calories here...
            try {
                multiple = (int)parent.getItemAtPosition(position) * constant.food_calories[constant.index];
                TextView tot_calories = (TextView) findViewById(R.id.caloriestotal);
                tot_calories.setText(multiple + "");
            } catch (NumberFormatException nfe) {
                Log.e("Error", "Failed to multiply invalid non-numbers");
            }
        }

        /**
         * Callback method to be invoked when the selection disappears from this view. 
         * The selection can disappear for instance when touch is activated or when the adapter becomes empty.
         * @param arg0
         */
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // You can also do something here, but not necessary
        }
    });