要實(shí)現(xiàn)spinner控件的級(jí)聯(lián)效果,可以通過(guò)在適配器中動(dòng)態(tài)設(shè)置下一個(gè)spinner的數(shù)據(jù)源來(lái)實(shí)現(xiàn)。具體步驟如下:
下面是一個(gè)簡(jiǎn)單的示例代碼,演示如何實(shí)現(xiàn)級(jí)聯(lián)效果:
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) {
}
});
以上代碼中,根據(jù)用戶在spinner1和spinner2中的選擇,動(dòng)態(tài)設(shè)置spinner2和spinner3的數(shù)據(jù)源,實(shí)現(xiàn)了級(jí)聯(lián)效果。您可以根據(jù)實(shí)際需求,調(diào)整數(shù)據(jù)源和邏輯,以滿足您的需求。