根据另一个下拉框中所选的项来更新下拉框。

3

这段代码有什么问题?

我有两个下拉菜单,一个是“类别”,另一个是“子类别”。当选择“类别”下拉菜单中的一个项目时,我想要重新加载相应的子类别。

        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) {

            }
        });

当活动被加载时,该代码被调用,并且成功地加载了第一个类别的子类别。然而,当我手动更改类别时,该代码被调用,但结果是子类别为空的旋转器。我无法弄清楚原因。有什么想法吗?

1个回答

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>而不是String[]

希望这可以帮到你。

实际上,使用ArrayList建议解决了问题。问题出在加载数组时犯了一个愚蠢的错误。谢谢。 - dsb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接