要實現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的數據源,實現了級聯效果。您可以根據實際需求,調整數據源和邏輯,以滿足您的需求。