我试图找出如何将两个微调器的值相乘并在TextView中显示答案。但是,代码会编译,应用程序在运行时会关闭。下面的代码是我目前使用的,但是,它不起作用。感谢。
spinnerStep1 =(Spinner) findViewById(R.id.step_1_spinner);
Integer[] step1 = new Integer[]{0,1,2,3,4,5};
ArrayAdapter<Integer> adapter1 = new ArrayAdapter<Integer> (this,R.layout.spinner_item, step1);
spinnerStep1.setAdapter(adapter1);
spinnerStep1.setOnItemSelectedListener(this);
spinnerStep2 =(Spinner) findViewById(R.id.step_2_spinner);
Integer[] step2 = new Integer[]{0,1,2,3,4,5};
ArrayAdapter<Integer> adapter2 = new ArrayAdapter<Integer>(this,R.layout.spinner_item, step2);
spinnerStep2.setAdapter(adapter2);
spinnerStep2.setOnItemSelectedListener(this);
drakeAnswer = (TextView) findViewById(R.id.drake_answer);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String myStr1 = spinnerStep1.getSelectedItem().toString();
String myStr2 = spinnerStep2.getSelectedItem().toString();
int myAnswer = 0;
try {
myAnswer = Integer.parseInt(myStr1) * Integer.parseInt(myStr2);
}catch(NumberFormatException nfe) {
}
drakeAnswer.setText(myAnswer);
}
答案 0 :(得分:2)
最佳做法是从onItemSelected方法中再次获取两个微调器和文本视图,您还需要确保在setText方法中设置字符串值:
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Spinner spinnerStep1 = (Spinner)findViewById(R.id.step_1_spinner);
Spinner spinnerStep2 = (Spinner)findViewById(R.id.step_2_spinner);
String myStr1 = spinnerStep1.getSelectedItem().toString();
String myStr2 = spinnerStep2.getSelectedItem().toString();
int myAnswer = 0;
try {
myAnswer = Integer.parseInt(myStr1) * Integer.parseInt(myStr2);
} catch(NumberFormatException nfe) {
Log.e("Error", "Failed to multiply invalid non-numbers");
}
TextView drakeAnswer = (TextView)findViewById(R.id.drake_answer);
drakeAnswer.setText("" + myAnswer);
}
答案 1 :(得分:0)
问题可能出在这一行
drakeAnswer.setText(myAnswer);
TextView的setText方法被重载,其中之一是:
setText(int resid)
您正在调用的是哪一个,并且可能没有像您传递的那样的resId。如果您想在 TextView 中编写 myAnswer ,请将其作为字符串传递:
drakeAnswer.setText(myAnswer);