我有一個意圖啓動與頁面上的一些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.
}
}
編輯我的主要職務,以顯示我的解決方案 - 感謝答案! (排除0) – Davek804