这是我的代码,我想将微调器的值与数组值相乘。
该数组从我的另一个名为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;
}
最佳答案
您可以使用以下代码解决此问题:
//Make these variables global so that it can be accessed in onClickListner.
Integer[] items = new Integer[]{1,2,3,4};
int multiple=0;
ImageView imageView;
TextView tot_calories;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_details);
Spinner mspin=(Spinner) findViewById(R.id.spinner1);
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]+"");
tot_calories=(TextView)findViewById(R.id.caloriestotal);
mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
multiple=items[i]*constant.food_calories[constant.index];
tot_calories.setText("update Value is: "+multiple);
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
}
更新了我的答案!因为我已经测试过自己,这是一个完整的解决方案。
关于java - 将微调器值与数组值相乘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35721062/