在Spinner中隐藏字符串数组值

时间:2015-09-21 08:09:28

标签: java android arrays android-spinner

我正在使用两个Spinners并使用相同的String数组填充它们:

final String[] arrayMonths = { "January", "Feburary", "March", "April", "May",
    "June", "July", "August", "September", "October", "November","December" };

现在我想进行一些小改动,我不想在 spinner1 中显示december,在 spinner2中显示January

那么我必须在代码中进行更改以完成此操作?

CODE

 adapter = new ArrayAdapter<String> (ConnectedSpinnersStartEnd.this, 
                android.R.layout.simple_spinner_item, arrayMonths);

 spinner1.setAdapter(adapter);

2 个答案:

答案 0 :(得分:1)

这比你想象的容易得多。第一步是从数组移动到ArrayList,这为您提供了更大的灵活性,并将其提交到ArrayAdapter而不是Array

ArrayList<String> mList = new ArrayList( Arrays.asList(arrayMonths));
mList.remove("December");
adapter = new ArrayAdapter<String> (ConnectedSpinnersStartEnd.this, 
        android.R.layout.simple_spinner_item, mList);

onItemSelected上,如果我理解正确,您要从第一个微调器中删除所选项目并将其添加到第二个微调器中,

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view,
            int position, long id) {
        String str1 = (String) parent.getItemAtPosition(position);
        if (spinner2.getAdapter() == null) {
               ArrayList<String> list =  new ArrayList( Arrays.asList(arrayMonths));
               list.remove("January");
               ArrayAdapter adapter = new ArrayAdapter<String>(ConnectedSpinnersStartEnd.this, android.R.layout.simple_spinner_item, list);
               spinner2.setAdapter(adapter);
        } 

我把它写在我的头顶,检查拼写错误

答案 1 :(得分:0)

将数组转换为列表后,您可以使用子列表:

https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-

喜欢:monthsList.subList(0,11)monthsList.subList(1,12)