2015-09-11 37 views
2

我有一個使用在getView()被重寫自定義適配器Spinner。我在捕獲OnItemSelected事件時遇到問題,我認爲這與自定義適配器有關。在我的onCreate(),我有這樣的:微調OnItemSelected使用自定義適配器

superGroupAdapter = new SuperGroupAdapter(context, R.layout.row_sg, sg_list); 
sgSpinner.setAdapter(superGroupAdapter); 

sgSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
    @Override 
    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) { 
     Log.d(Constants.TAG, "sg spinner on item selected"); 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> adapterView) { 

    } 
}); 

這是我的自定義適配器類:

public class SuperGroupAdapter extends ArrayAdapter<String> { 

    @Inject SharedVisualElements sharedVisualElements; 

    Context context; 
    ArrayList<String> sg_list; 

    public SuperGroupAdapter(Context context, int textViewResourceId, ArrayList<String> sg_list) { 
     super(context, textViewResourceId, sg_list); 

     // add this line for any class that want to use any of the singleton objects 
     Injector.INSTANCE.getAppComponent().inject(this); 

     this.context = context; 
     this.sg_list = sg_list; 
    } 

    @Override 
    public View getDropDownView(int position, View convertView, ViewGroup parent) { 
     return getCustomView(position, convertView, parent); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     return getCustomView(position, convertView, parent); 
    } 

    public View getCustomView(int position, View convertView, ViewGroup parent) { 

     parent.setBackgroundColor(sharedVisualElements.backgroundColor()); 

     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View row = inflater.inflate(R.layout.row_sg, parent, false); 

     TextView label = (TextView) row.findViewById(R.id.sg_name); 
     label.setText(sg_list.get(position)); 
     label.setTypeface(sharedVisualElements.font()); 
     label.setTextColor(sharedVisualElements.primaryFontColor()); 
     label.setGravity(Gravity.CENTER_HORIZONTAL); 

     return row; 
    } 
} 

當活動初始化,我看到日誌輸出

SG微調在項目選擇

但是,這是我最後一次看到它。無論我從微調器中選擇一件物品多少次,它都不會再次發射。我一直在尋找一種方法來捕捉這一點,但無濟於事。誰能幫忙?謝謝。

編輯 我也試着改變類簽名以實現OnItemSelected並宣佈聽者作爲一個單獨的方法,在Android docs進行了說明,但得到了同樣的結果。

我認真的在這一個損失。我感謝任何幫助。

回答

3

好吧,我想通了這一點。在回顧了其他一些帖子後,我發現在我的測試數據中,我的微調列表中只有一個項目。 OnItemSelectedListener只有在您選擇更改時纔會觸發。

從Android文檔爲OnItemSelectedListener

此回調時,新選擇的位置是 從先前選定的位置不同時才調用或如果沒有 選擇的項目。

因此,當活動初始化時,它選擇位置0處的項目。當我點擊微調框並選擇了相同的項目時,此操作不會觸發該事件。活到老,學到老。

1

我覺得適配器SuperGroupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

+0

謝謝,但這並沒有解決問題。 – Alex

1

嘗試之前你錯過這個調用superGroupAdapter.notifyDataSetChanged()添加項之後sg_list或改變sg_list

+0

謝謝。我從來沒有改變sg_list一旦創建,所以我不認爲這是問題。我試過了,以防萬一,但它沒有改變任何東西。 – Alex