2011-03-17 47 views
0

我想拥有三个内容相互依赖的Spinners。Android:更改ArrayAdapter的微调器 - 如何识别?

E.g.根据是否在Spinner1上选择item1或item2,Spinner1显示{item1,item2}和Spinner2 {item3,item4}或{item5,item6}。 与Spinner 3相同,它对Spinner1和/或Spinner2的变化做出反应。

对于后者,我必须确定第一哪种可能的值集在Spinner2大气压所示。

我的问题是一种类似于this question,但我不知道得到适配器后做什么。

这是我到目前为止有:

ArrayAdapter adapter1 = (ArrayAdapter) spinner2.getAdapter(); 
if(items_spinner1[0].contentEquals(adapter1.getItem(0))) 
{ 
    //... 
} 

我得到的适配器,问的第一个值,并将它与我的阵列,以确定它的第一个字符串值。这对我来说似乎并不高雅。有更简单的解决方案吗?

回答

0

你说以后微调的内容依赖于早期的的选择,但你发布的代码只依赖于内容的微调的

adapter1.getItem(0)返回列表中的第一个项目,而不是当前选择的项目。要获取当前选择的项目,请使用微调器(不是适配器)的getSelectedItem()方法。

你可以,例如,把你的第一个微调的onItemSelectedListener这样的事情(编辑基于以下您的评论):

public void onItemSelected (AdapterView<?> parent, View view, int position, long id) { 
    Object selectedItem = parent.getSelectedItem(); 

    // Do this if the first Spinner has a set of options that are 
    // known in advance. 
    if (/*selectedItem is something*/) { 
     // Set up the second Spinner in some way 
    } else if (/*selectedItem is something else*/) { 
     // Set up the second Spinner in another way 
    } 

    // OR, if you need to do something more complex 
    // that would cause too much clutter here, do this. 
    fillSecondSpinner(selectedItem); 
} 

然后将其放置在第二微调的onItemSelectedListener类似的东西。使用getSelectedItem()(或者第一个使用getSelectedItemId(),第二个使用位置参数)获取第一个和第二个Spinners中的选定项目。使用选定的项目设置第三个。

编辑:的OnItemSelectedListener第二微调会是这个样子。

// This must be defined in the enclosing scope. 
final Spinner firstSpinner; // Must be final to be accessible from inner class. 
Spinner secondSpinner; 
// ... 
secondSpinner.setOnItemSelectedListener(new OnItemSelectedListener { 
    public void onItemSelected (AdapterView<?> parent, View view, int position, long id) { 
     // Again, usually the selected items should be of 
     // a more specific type than Object. 
     Object firstSelection = firstSpinner.getSelectedItem(); 
     Object secondSelection = parent.getSelectedItem(); 

     fillThirdSpinner(firstSelection, secondSelection); 
    } 

public void onNothingSelected (AdapterView<?> parent) { } 
}); 
+0

“你说后面的spinners的内容取决于前面的选择,但是你发布的代码只取决于spinner的内容。” - 对不起,我没有把自己弄清楚...... Spinner2的内容只取决于Spinner1的选择,但Spinner3的内容取决于Spinner2的选择和内容。 (它应该通过树结构导航用户。) 我已经找到了选择部分,所以我现在正在寻找一种方法来确定第二个Spinner的内容。 – jellyfish 2011-03-18 08:56:04

+0

如果没有简单的方法,我可以保存一个标志,在Spinner1中选择后,我添加到Spinner2中的内容。但是因为我不知道Spinner2可能有多少可能的内容,所以我宁愿找到另一种方式。 – jellyfish 2011-03-18 08:57:50

+0

@jellyfish:据我所知,除非你让自己的Adapter直接暴露它的数据模型,否则getItem(int)是查看内容的唯一方法。但是,如果第二个Spinner的内容取决于第一个选择的内容,那么您可以很容易地看到第一个选择是什么。您还可以保留对传递给第二个适配器的数组(或列表)的引用,并确保数组始终更新为正确的数组。 – erichamion 2011-03-18 14:39:54

相关问题