2012-05-18 17 views
1

我有一個意圖啓動與頁面上的一些spinners的活動。我剛剛設置了我的微調器的ItemSelected監聽器,遵循this指南。問題是,每個Spinner中的第一個項目基本上都是「請選擇」,因此它不是一個空白框:所以我的ItemSelected Listener檢測到請選擇是在微調器中,似乎假定它被選中而不是加載默認。理想情況下,我希望聽衆只在發生實際選擇時才能檢測到。忽略默認選擇的最佳方式是什麼?Spinner's Listener檢測到默認/顯示選項爲ItemSelected? (已解決)

下面是相關代碼:

ageSpinner = (Spinner) findViewById(R.id.ageSpinner); 
    ageAdapter = ArrayAdapter.createFromResource 
    (this, R.array.ageArray, android.R.layout.simple_spinner_item); 
    ageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    ageSpinner.setAdapter(ageAdapter); 
    ageSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); 

public class MyOnItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, 
     View view, int pos, long id) { 
     Toast.makeText(parent.getContext(), "The planet is " + 
      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); 
    } 

    public void onNothingSelected(AdapterView parent) { 
     // Do nothing. 
    } 
} 

編輯〜解決方案

public class MyOnItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, 
     View view, int pos, long id) { 
     if (pos != 0) { 
     //this if makes sure it ignores 0, which is 
      //Please Select in the drop down  
     Toast.makeText(parent.getContext(), parent.getTag().toString() + 
      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); 
     } 
    } 

    public void onNothingSelected(AdapterView parent) { 
     // Do nothing. 
    } 
} 

回答

1

問題在於選擇是在第一個佈局階段完成的。因此,第一次計算佈局時,Spinner會提高onItemSelected。它非常煩人,但它的工作方式。你可以嘗試一些不同的東西,但鑑於你已經有請選擇一些東西項目,你能做的最好的就是忽略該事件時所選擇的項目爲0

+0

編輯我的主要職務,以顯示我的解決方案 - 感謝答案! (排除0) – Davek804

1

設置一個布爾值false時,檢查它在onItemSelected而如果爲假,將其設置爲true,別的什麼也不做。下一次,如果真的如你所願的那樣做。

1

這裏有很多可行的方法。例如,您可以使用反射覆蓋Spinner的正常行爲,或者直接切換到模仿SpinnerButton,點擊它後彈出AlertDialog

但是,其他解決方案可以更容易實現。巴拉克已經命名了一個,而另一種方法是簡單地檢查Spinner中的選定位置,假設「請選擇」將始終是第一項(因此,在位置0),並且您沒有進行任何排序項目。

我相信你會發現適合你的問題的可能性之一,但也許你也可以詳細說明爲什麼它的問題onItemSelected(...)被初始選擇解僱了嗎?