2011-05-28 121 views
1

我必須創建一個不在我的佈局中的微調器。以編程方式創建微調器

所以我想創建它編程我寫了下面的代碼在我的活動類

Spinner spinner = new Spinner(this); 
String option[]={"By Date","By Transaction ID","By Customer Phone"}; 
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,option); 
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
spinner.setAdapter(spinnerArrayAdapter); 
spinner.performClick(); 
spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 

    @Override 
    public void onItemSelected(AdapterView<?> parentview, View v,int position, long id) 
    { 
     Log.d("in select","yes"); 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0) 
    { 
     Toast.makeText(MainMenu.this,"no",Toast.LENGTH_LONG).show(); 
     Log.d("In No select","No"); 
    } 
}); 

所以我的問題是如何訪問微調所選的項目,活動

回答

1

在你onItemSelected

@Override 
public void onItemSelected(AdapterView<?> parentview, View v,int position, long id) 
{ 
    Log.d("in select","yes"); 
} 

position幫助您找回您選擇的項目。其中,在你的情況下,它應該是:

option[position] 
+0

感謝答覆,但onItemSelected函數不叫,所以我如何檢索值,而不調用它,它爲什麼不叫 – 2011-05-28 00:41:45

+0

呀只要把你的支持數組中的活動,並使用當前位置找出哪個東西被選中。 – 2011-05-28 00:44:34

+0

我的數組已經在活動中了,我看到spinner的視圖非常好,但是當我選擇任何項目的時候沒有任何反應 – 2011-05-28 00:46:59

1

你訪問它偵聽器之外唯一的辦法就是做一個變量,保持姿勢,所以你以後會使用它。 事情是這樣的:

public class YourActivity extends Activity { 
    private int curPos; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

    Spinner spinner = new Spinner(this); 
    String option[]={"By Date","By Transaction ID","By Customer Phone"}; 
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,option); 
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinner.setAdapter(spinnerArrayAdapter); 
    spinner.performClick(); 
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 

     @Override 
     public void onItemSelected(AdapterView<?> parentview, View v,int position, long id) 
     { 
      curPos = position; 
      Log.d("in select","yes"); 
     } 

     @Override 
     public void onNothingSelected(AdapterView<?> arg0) 
     { 
      Toast.makeText(MainMenu.this,"no",Toast.LENGTH_LONG).show(); 
      Log.d("In No select","No"); 
     } 
    }); 
} 
+0

嘿,我認爲你不太明白,我的問題是執行沒有達到onItemSelected塊 – 2011-05-28 00:58:19

+0

哦,抱歉。 您是否嘗試調試它,並在「onItemSelected」方法的開頭放置一個斷點? – Elad92 2011-05-28 01:09:00

+0

是的,但沒有執行此方法 – 2011-05-28 01:13:21