2013-11-14 129 views
0

我有一個自定義枚舉類:檢索值的自定義枚舉

public static enum Frequency_Unit{ 
    MINUTES("Minutes", 0), 
    HOURS("Hours", 1), 
    DAYS("Days", 2), 
    WEEKS("Weeks", 3), 
    MONTHS("Months", 4), 
    YEARS("Years", 5); 

    private String stringValue; 
    private int intValue; 
    private Frequency_Unit(String toString, int value) { 
     this.stringValue = toString; 
     this.intValue = value; 
    } 

    @Override 
    public String toString() { 
     return stringValue; 
    } 
} 

我用它來建立一個微調:

spinner_frequency = (Spinner) findViewById(R.id.spinner_repeat_frequency); 
spinner_frequency.setAdapter(new ArrayAdapter<Constants.Frequency_Unit>(this, 
    android.R.layout.simple_spinner_item, Constants.Frequency_Unit.values())); 

現在我想檢索與onItemSelectedListener數值(即1,如果用戶選擇「時間」):

spinner_frequency.setOnItemSelectedListener(spinner_frequency_listener); 

但監聽器本身,我不知道該如何檢索值。

OnItemSelectedListener spinner_frequency_listener = new OnItemSelectedListener() 
{  
    public void onItemSelected(AdapterView<?> parent, View view, 
      int pos, long id) { 
     if (parent.getChildCount() > 0){ 
      int repeat_frequency = //**VALUE SHOULD BE HERE** 
     } 
    } 


    // Default line, when nothing is selected 
    public void onNothingSelected(AdapterView<?> arg0) {  

    } 
}; 

怎麼辦?

回答

1

使簡單通過調用如下:

@Override 
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
    Frequency_Unit freq = (Frequency_Unit) parent.getItemAtPosition(pos); 

    //do whatever with 'freq' 
} 
+0

沒錯,就是工作!只需要將一些getters添加到Frequency_Unit類中,然後使用'repeat_frequency = freq.getIntValue();'。非常感謝你! – Igal

1
@Override 
      public void onItemSelected(AdapterView<?> parent, 
       View arg1, int position, long arg3) { 
       Beantype genreBean = (Beantype) parent 
        .getItemAtPosition(position); 
}