我必须基于微调器开发应用程序。
所以我把spinner1作为产品选择,我必须给spinner2数据。这是在特定的产品类别中,所以我必须在spinner1的基本选择上更新spinner2。
我搜索了很多,但我可以获得任何确定的示例代码或资源。所以请帮我这样做。
答案 0 :(得分:1)
我同意@ user639183,有很多类似的问题......但是,有一些关于你如何做的解释:
OnItemSelected
spinner1.setOnItemSelectedListener(...)
事件
步骤1的示例:
private String[] spinner1values = new String[] { "cat1", "cat2" };
private String[][] spinner2values = new String[][] {
new String[] { "a1", "b1", "c1" },
new String[] { "a2", "b2" }
};
spinner1的人口如下:
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinner1values);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
如果你阅读了Spinners的文档和示例,那么到目前为止这是绝对直截了当的。
接下来,请加入OnItemSelectedListener
:
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// create a new adapter with the corresponding values
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(arg0.getContext(),
android.R.layout.simple_spinner_item, spinner2values[position]);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// set adapter
((Spinner)findViewById(R.id.spinner2)).setAdapter(adapter2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// nothing selected, so set empty options
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(arg0.getContext(),
android.R.layout.simple_spinner_item, new String[0]);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
((Spinner)findViewById(R.id.spinner2)).setAdapter(adapter2);
}
});
请注意,spinner2values
中数组的顺序与类别值的顺序相对应!