2011-04-29 135 views
0
public class testAddSpiner extends Activity { 
private Spinner m_myDynamicSpinner; 
private EditText m_addItemText; 
private ArrayAdapter<CharSequence> m_adapterForSpinner; 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);   
    m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText); 
    Button addButton = (Button)findViewById(R.id.AddBtn); 
    Button clearButton = (Button)findViewById(R.id.ClearBtn); 


    m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item); 
    m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   
    m_myDynamicSpinner.setAdapter(m_adapterForSpinner); 
    m_adapterForSpinner.add("gr");   


    addButton.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) {    
      addNewSpinnerItem(); 
     }     
    }); 


    clearButton.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      clearSpinnerItems(); 
     }   
    }); 
} 

private void addNewSpinnerItem() { 
    CharSequence textHolder = "" + m_addItemText.getText(); 
    m_adapterForSpinner.add(textHolder); 

} 

private void clearSpinnerItems() { 
    m_adapterForSpinner.clear(); 
    m_adapterForSpinner.add("dummy item"); 
}  

} 

我的微調m_adapterForSpinner是更新得非常好沒有更新數據,而如果我選擇一個從m_adapterForSpinner,它可以在spinner.i顯示想要做的是,我添加一個數據不僅顯示在m_adapterForSpinner上,而且還顯示在微調器上。動態數據添加到微調器,但是,微調

private void addNewSpinnerItem() { 
    CharSequence textHolder = "" + m_addItemText.getText(); 
    m_adapterForSpinner.add(textHolder); 
    m_adapterForSpinner.notifyDataSetChanged(); 

} 

回答

1
addButton.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) {    
      addNewSpinnerItem(); 
      int a= m_adapterForSpinner.getCount(); 
      m_myDynamicSpinner.setSelection(a-1); 

      // m_adapterForSpinner.notifyDataSetChanged(); 
     }     
    }); 
0

嘗試將項目添加到適配器後,調用notifyDataSetChanged()? spinner.setSelection(0);

+0

可能你不明白我的問題,我想更新三角形左邊的數據,我的代碼可以更新setDropDownViewResource中的微調框。當我點擊該項目時,三角形左側的數據是更新的,所以我希望當我添加數據時,微調器一次更新,不需要點擊。 – pengwang 2011-04-29 06:45:00

1

您試圖選擇第一項:

+0

但我添加數據到m_adapterForSpinner是在最後,不是在第一,spinner.setSelection(0)總是顯示第一個,所以不能滿足我的需要 – pengwang 2011-04-29 08:08:33

+0

好吧,然後我沒有得到你的問題 – ernazm 2011-04-29 08:10:28

+0

謝謝你你的線索,我解決了它。 – pengwang 2011-04-29 08:11:14