为什么在setSelection之后onItemSelected不直接触发?

时间:2015-03-31 10:27:59

标签: android android-spinner

为什么onItemSelected不会在transportMode上的setSelection之后直接触发,而是仅在populateEditData方法完成之后?

我需要启动onItemSelected,因为我根据为transportMode选择的值动态更改onItemSelected中传输公司的数据集

protected void onCreate(Bundle savedInstanceState)
{
   transportMode = (Spinner) findViewById(R.id.spnrTransportMode);
   transportModeAdapter = new CustomSpinnerAdapter(this, R.id.txtvTransporModeSpinner, R.layout.custom_spinner_row_item_mode, getResources().getStringArray(R.array.transport_mode_array), "mode");
   transportMode.setAdapter(transportModeAdapter);
   transportMode.setOnItemSelectedListener(this);

   transportCompany = (Spinner) findViewById(R.id.spnrTransportCompany);
    transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvTransportCompany, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_bus_companies_array), "company");
    transportCompany.setAdapter(transportCompanyAdapter);

   ....

   if(useActivityForEdit)
        populateEditData();
}

public void populateEditData(int modeIndex, int companyIndex)
{
   //Two spinners transportMode has onItemSelected listener
   transportMode.setSelection(modeIndex);
   //On item selected should trigger here then complete before setting transport company selection
   transportCompany.setSelection(companyIndex);
}

public void onItemSelected(AdapterView<?> arg0, View view, int selectedIndex, long arg3) 
{
   //dynamically changes data of transportCompany adapter
   if(transportMode.getSelectedItem().toString().equalsIgnoreCase("bus"))
   {    
    transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_bus_companies_array), "company");
    transportCompany.setAdapter(transportCompanyAdapter);
    transportCompany.setClickable(true);
   }
   else if(transportMode.getSelectedItem().toString().equalsIgnoreCase("train"))
   {
    transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_train_companies_array), "company");
    transportCompany.setAdapter(transportCompanyAdapter);
    transportCompany.setClickable(true);
   }
   else if(transportMode.getSelectedItem().toString().equalsIgnoreCase("tram"))
   {
    transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_tram_companies_array), "company");
    transportCompany.setAdapter(transportCompanyAdapter);
    transportCompany.setClickable(true);
   }
}

1 个答案:

答案 0 :(得分:0)

尝试在transportCompany.setAdapter(transportCompanyAdapter);之后添加transportCompany.setSelection(companyIndex);

并在transportMode.setAdapter(transportModeAdapter);之后添加transportMode.setSelection(modeIndex);