我有一个带有类别列表的Spinner,它从JSON获取数据。我想使当所有类别以外的项目被选中时,另一个子类别的微调变得可见,并根据其类别从JSON加载数据。

以前我设法做到了,但是将其放置几天并完成其他部分后,它不再起作用。

由于加载到微调器中的第一个是“所有类别”,因此它触发了setOnItemSelectedListener()并隐藏了subcategorySpinner。如果选择了其他项目,subcategorySpinner仍不会显示。

代码逻辑有问题吗?请帮忙。

categorySpinner = (Spinner) rootView.findViewById(R.id.categorySpinner);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, categoryList);
adapter2.setDropDownViewResource(R.layout.spinner_dropdown_item);
categorySpinner.setAdapter(adapter2);

categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
categoryString = categorySpinner.getSelectedItem().toString().replace(" ", "%20");
if (categorySpinner.getSelectedItem().toString().equals("All Category")) {
   Log.d("debug", "all category");
   subcategorySpinner.setVisibility(View.GONE);
} else {
   Log.d("debug", "other than all category");
   subcategorySpinner.setVisibility(View.VISIBLE);
   generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}


});

最佳答案

将您的代码更改为

categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


// On selecting a spinner item
categoryString = parent.getItemAtPosition(position).toString();
Log.d("debug", categoryString+"..."+position);

if (categoryString.equals("All Category")) {
   Log.d("debug", "all category");
   subcategorySpinner.setVisibility(View.GONE);
} else {
   Log.d("debug", "other than all category");
   subcategorySpinner.setVisibility(View.VISIBLE);

   categoryString = categoryString.replace(" ", "%20")
   generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}

08-18 08:59