2010-08-02 124 views

回答

1
spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 
     @Override 
     public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { 
      // your code here 
     } 

     @Override 
     public void onNothingSelected(AdapterView<?> parentView) { 
      // your code here 
     } 

    }); 

注:

Spinner widget的文件中明確指出:

A spinner does not support item click events. Calling this 
method will raise an exception. 

更好地利用 OnItemSelectedListener()代替,如上面。

0

在你的活動:

public void onItemSelected(AdapterView<?> parent, View view, int position, long id{ 
    SpinnerData sd; 


    switch (parent.getId()) { 

    case R.id.my_spinner: 
     sd = (SpinnerData)mSpinner.getSelectedItem(); 
     // do something with sd.id 
     break; 

... }

參考:

mSpinner = (Spinner) findViewById(R.id.my_spinner); 

// Define your adapter, in my case I have a class (SpinnerData) so I get an ID instead of the spinner's text 
ArrayAdapter<SpinnerData> myadapter = new ArrayAdapter<SpinnerData>(
    this, android.R.layout.simple_spinner_item, new SpinnerData [] { 
    new SpinnerData("1","Item 1"), 
    new SpinnerData("2","Item 2") 
}); 

myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    mSpinner.setAdapter(myadapter); 
    mSpinner.setOnItemSelectedListener(this); 

如果你在形式與其他元素觸發onItemSelected事件,這非常有用,SpinnerData類:

public class SpinnerData { 

public String id; 
public String name; 

public SpinnerData(String _id, String _name) { 

    this.id = _id; 
    this.name = _name; 

} 

public String toString() { 
    return this.name; 
} 

} 

希望它有幫助。

0

試試這個代碼..

sp2.setOnItemSelectedListener(new OnItemSelectedListener() 
{ 

     @Override 
     public void onItemSelected(AdapterView<?> arg0, View arg1, 
        int arg2, long id) { 
     // TODO Auto-generated method stub 
     int selected_item_position = arg2; 
     String selected_item=sp2.getSelectedItem().toString(); 

     } 

     @Override 
     public void onNothingSelected(AdapterView<?> arg0) { 
     // TODO Auto-generated method stub 

     } 
}); 
相關問題