我正在尝试在一个活动中实现多个微调器,这似乎工作正常。我遇到的问题是当我尝试使用onItemSelected输出他们的选项时,我无法弄清楚如何告诉这个方法哪个微调器刚刚更新。我将复制代码,但这里是onItemSelected方法的摘录。例如,如果我有两个微调器只会显示intTypeItems微调器的结果。
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(intTypeItems[position]);
}
以下是我正在使用的完整课程。
public class Calculator extends Activity implements AdapterView.OnItemSelectedListener {
private TextView selection;
private static final Integer[] intNoItems={1,2,3};
//private static final String[] intNoItems={"one","two","three"};
private static final String[] intTypeItems={"Seconds","Minutes","Hours","Days"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
Spinner intNo=(Spinner)findViewById(R.id.intervalNo);
Spinner intType=(Spinner)findViewById(R.id.intervalType);
intNo.setOnItemSelectedListener(this);
intType.setOnItemSelectedListener(this);
selection=(TextView)findViewById(R.id.outPutValues);
ArrayAdapter<Integer> intNolist=new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item,intNoItems);
ArrayAdapter<String> intTypelist=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,intTypeItems);
intNolist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
intTypelist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
intNo.setAdapter(intNolist);
intType.setAdapter(intTypelist);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(casting + intTypeItems[position]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
其中一个微调器是另一个字符串的int,因此我还需要在输出到我的选择文本视图时将int强制转换为字符串。我再也不知道怎么做,因为当字符串获得回调时,强制转换会导致异常?
答案 0 :(得分:1)
您已为两个微调器附加了相同的侦听器。干净的方式可能会为每个人使用不同的听众
intNo.setOnItemSelectedListener(new FirstListener());
intType.setOnItemSelectedListener(new SecondListener());
编写两个独立的内部类,FirstListener和SecondListener
OR
匿名内部类似下面的内容
intNo.setOnItemSelectedListener(
new View.OnClickListener() {
public void onClick(View v) {
//Your code here.
}
}
);
答案 1 :(得分:1)
你应该拥有所需的一切。看看电话:
public void onItemSelected(AdapterView<?> parent, View v, int position, long id);
第一个参数parent
包含项目所属的View
。在您的情况下,它将是intNo
或intType
。如果您将这些变量保留为字段,则可以测试以查看您所在的Spinner
,如下所示:
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
if(parent == intNo) {
selection.setText(casting + intNoItems[position]);
} else if(parent == intType) {
selection.setText(casting + intTypeItems[position]);
}
}