此代码有什么问题?
我有两个旋转器。一个用于'类别'和第二个“子类别”#。当在类别微调器中选择一个项目时,我想相应地重新加载相关的子类别。
mSpnrCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// SubCategories
String[] aSubCategory = new String[SUBCATS.length];
... Some code for preparing aSubCategory.
ArrayAdapter<String> dataAdapterSubCategories = new ArrayAdapter<String>(NewRequestActivity.this, android.R.layout.simple_spinner_item, aSubCategory);
dataAdapterSubCategories.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpnrSubCategory.setAdapter(dataAdapterSubCategories);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
加载活动时,会调用此代码,并且可以正常加载第一个类别的子类别。但是,当我手动更改类别时,将调用此代码,但结果为子类别的空微调器。我无法弄清楚原因。有什么想法吗?
答案 0 :(得分:2)
将子类别适配器(mSpnrSubCategory
)定义为全局变量
然后,每当类别微调器单击时,更改子类别的数据,然后更改notifyDataSetChanged();
ArrayAdapter<String> mSpnrSubCategory;
ArrayList<String> aSubCategory;
mSpnrCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// SubCategories
...
mSpnrSubCategory.notifyDataSetChanged();
}
});
我建议使用ArrayList<String> instead of String[]
希望这个帮助