2015-08-20 61 views
0

我嘗試創建兩個相關spinners。我知道這類問題已經綽綽有餘,但沒有解決我的問題。看起來onItemSelected根本不開火。當第一個微調(divisions_spinner)被選中或改變時,我想要第二個(townships_spinner)改變。比方說,當我選擇希望僅顯示來自給定州的城市的州時,我擁有州和城市。紡紗機是動態創造的。Android依賴spinners - onItemSelected不會觸發

這是我的代碼:

public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener { 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ... 
    createLayout(); 
    } 

    public void createLayout(){ 
    division_spinner = new Spinner(this); 

    ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList()); 
    divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname()); 
    division_spinner.setAdapter(division_adapter); 
    division_spinner.setSelection(divisions.getIndex(divisions_id)); 
    division_spinner.setOnItemSelectedListener(this); 

    township_spinner = new Spinner(this); 
    ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id)); 
    if (divisions_id == null) { 
     township_spinner.setEnabled(false); 
    } 
    String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname()); 
    township_spinner.setSelection(townships.getIndex(value, divisions_id)); 
    } 

    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) { 

    Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG); 
    if(arg0.equals(division_spinner)) { 
     Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG); 

     township_spinner.setEnabled(true); 
     ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString())); 
     township_spinner.setAdapter(township_adapter); 
    } 
    } 

    public void onNothingSelected(AdapterView<?> arg0) { 

    } 
} 

但是, 「是的」,甚至 「是的 - 你得到它!」烤麪包沒有出現。

我想我錯過了一些愚蠢的東西,但我無法找到它。

回答

0

我犯了一系列錯誤,導致它沒有按預期工作。

第一:我忘了打電話給**show()**Toast.makeText()

二:我做一個巨大的錯誤創建ArrayList時。我用數據填充了ArrayList,然後我把列表放到了HashMap之後,之後我打電話給ArrayList.**clear()**。這導致了覆蓋HashMap的價值觀,這就是爲什麼它似乎,微調並沒有改變在所有...

嗯......我覺得挺傻......

1

你正在實現AdapterView.onItemSelected。

...只是試試這個,而不是

Spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
{ 
    @Override 
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
{ 
    Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show(); 
    //Call other spinner here to update. 
} 

@Override 
public void onNothingSelected(AdapterView<?> parentView) 
{ 
    Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show(); 
} 
}); 

編輯:作爲普拉薩德說。如果你沒有setContentView(View);你的活動不會有xml膨脹,所以你的視圖永遠不會被創建成任何東西。

+1

謝謝回答,但我的代碼也適用。 Toast.makeText().SHOW()...我的錯,我很抱歉... +1 .show() – kristyna