要实现spinner控件的级联效果,可以通过在适配器中动态设置下一个spinner的数据源来实现。具体步骤如下:
下面是一个简单的示例代码,演示如何实现级联效果:
Spinner spinner1 = findViewById(R.id.spinner1);
Spinner spinner2 = findViewById(R.id.spinner2);
Spinner spinner3 = findViewById(R.id.spinner3);
String[] options1 = {"Option 1", "Option 2", "Option 3"};
String[][] options2 = {{"Option A1", "Option A2"}, {"Option B1", "Option B2"}, {"Option C1", "Option C2"}};
String[][][] options3 = {{{"Option X1", "Option X2"}, {"Option Y1", "Option Y2"}}, {{"Option Z1", "Option Z2"}, {"Option W1", "Option W2"}}};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, options1);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, options2[position]);
spinner2.setAdapter(adapter2);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter<String> adapter3 = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, options3[spinner1.getSelectedItemPosition()][position]);
spinner3.setAdapter(adapter3);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
以上代码中,根据用户在spinner1和spinner2中的选择,动态设置spinner2和spinner3的数据源,实现了级联效果。您可以根据实际需求,调整数据源和逻辑,以满足您的需求。