2012-02-13 66 views
30

我有兩個微調(day_spin和time_spin)在一個Activity。我想將選定的day_spin值保存到變量中。在同一Listener的兩個紡紗廠之間是否可以區分?還是我必須爲每個微調器寫我自己的Listener類?Android:兩個微調onItemSelected()

另外我想獲得所選項目的編號。例如,我有6個元素的字符串數組。我選擇了3號。我怎樣才能得到這個ID?

day_spin = (Spinner) findViewById(R.id.spinner); 
    ArrayAdapter<CharSequence> adapter_day = ArrayAdapter 
      .createFromResource(this, R.array.spinner_day_array, 
        android.R.layout.simple_spinner_item); 
    adapter_day 
      .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    day_spin.setAdapter(adapter_day); 
    day_spin.setOnItemSelectedListener(this); 

    time_spin = (Spinner) findViewById(R.id.spinner1); 
    ArrayAdapter<CharSequence> adapter_time = ArrayAdapter 
      .createFromResource(this, R.array.spinner_time_array, 
        android.R.layout.simple_spinner_item); 
    adapter_time 
      .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    time_spin.setAdapter(adapter_time); 
    time_spin.setOnItemSelectedListener(this); 

這是我Listener

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
    DAY = parent.getItemAtPosition(pos).toString(); 
    TIME = parent.getItemAtPosition(pos).toString(); 
} 

我希望你能幫幫我!

回答

96
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 

    Spinner spinner = (Spinner) parent; 
    if(spinner.getId() == R.id.spinner1) 
    { 
     //do this      
    } 
    else if(spinner.getId() == R.id.spinner2) 
    { 
     //do this 
    } 

} 
+3

SWITH是最好的方式,(如果其他人)是新人 – Cabezas 2014-10-27 17:04:53

+3

@Yaqub相反的類型轉換,我們可以利用的getId的'()'調用直。 if(parent.getId()== R.id.spinner1)''if(parent.getId()== spinnerView.getId()){...}' – blizzard 2015-05-14 14:24:18

+0

' '' – nyxee 2017-01-29 11:46:56

3

onItemSelected方法

int i = spinnerFirst.getSelectedItemPosition(); 
int j = spinnerSecond.getSelectedItemPosition(); 

String strName1 = yourFirstarray[i]; 
String strName2 = yourSecondarray[j]; 
16
public void onItemSelected(AdapterView<?> parent, View view, 
     int pos, long id) { 
    // An item was selected. You can retrieve the selected item using 
    //parent.getItemAtPosition(pos); 

    //Spinner spnir = (Spinner)parent; 

    parent.getItemAtPosition(pos); 

    TextView tvReadValue = (TextView) findViewById(R.id.tvReadValue); 
    switch (parent.getId()) 
    {   
     case R.id.spinDimension: 

      tvReadValue.setText("spinDimension" + pos); 

      break;    

     case R.id.speedDimension: 

      tvReadValue.setText("speedDimension" + pos); 
      break;    
    } 
相關問題