2017-03-06 95 views
0

我在我的應用程序中創建了Spinner,當我做一些事情時我正在更改我的適配器。更改後,當我打開微調器時,它應刷新名稱列表,但它保持不變。當我檢查適配器時,我可以看到該列表已刷新正確,但未顯示在微調器中。這裏是我的代碼:微調不改變,但適配器

public void addItemsToSpinner(UserSettings settings) { 
    List<Recipient> list = settings.getRecipients(); 

    Recipient selectedRecipient = settings.getSelectedRecipient(); 

    List<String> nicks = new ArrayList<>(); 

    if (selectedRecipient != null) { 
     Log.d("utolsó","selected name " + selectedRecipient.getNickname()); 
     nicks.add(selectedRecipient.getNickname()); 
    } 
    for (Recipient recipient: list) { 
     if (selectedRecipient == null || !recipient.getNickname().equals(selectedRecipient.getNickname())) { 

      nicks.add(recipient.getNickname()); 
     } 
    } 

    for(int i = 0 ;i<nicks.size();i++){ 
     Log.d("TAG","print the order = " + nicks.get(i)); 
    } 

    dataAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item, nicks); 
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    mSpinner.setAdapter(dataAdapter); 
    dataAdapter.notifyDataSetChanged(); 
} 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.dialog_recipient_chooser, container, false); 
    mSpinner = (Spinner) view.findViewById(R.id.spinnerChooser); 
    mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
     @Override 
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
      dataAdapter.notifyDataSetChanged(); 
      if (mListener != null) { 
       mListener.onRecipientSelected(position); 
      } 
     } 

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

     } 
    }); 
    return view; 
} 

當我的命令是正確的,但在微調不是。誰能告訴我爲什麼?

+0

通知適配器()後,您嘗試使用adapter.notifyDataSetChanged();; –

+0

我在onItemSelected中做過。我應該在哪裏做?在將適配器設置爲微調器之前? –

+0

當您將新項目添加到列表時,您應該通知您的適配器。所以在將項目添加到nicks列表之後。 –

回答

0

有列表添加items..dataAdapter.notifyDataSetChanged後改變

+0

在設置適配器並將新項目添加到列表後,您應該執行此操作 –

+0

我已經編輯了我的代碼,現在您可以看到我在哪裏調用它。然後在日誌中列表的順序是正確的,但微調框中的第一個對象又是錯誤的 –

+0

瞭解它,因爲你在這裏添加第一個項目,如果(selectedRecipient!= null){012,Log.d(「utolsó」,「selected名稱「+ selectedRecipient.getNickname()); nicks.add(selectedRecipient.getNickname()); } –