2011-03-17 31 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