Android依赖的微调器 - onItemSelected不会触发

时间:2015-08-20 19:14:01

标签: android onitemselectedlistener

我尝试创建两个依赖的微调器。我知道这类问题已经绰绰有余了,但没有解决我的问题。似乎onItemSelected根本不会发射。我希望在选择或更改第一个微调器(divisions_spinner)时更改第二个(townships_spinner)。让我们说我有州和城市,当我选择州时想要只显示来自特定州的城市。旋转器是动态创建的。

那是我的代码:

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) {

  }
}

但&#34;是&#34;甚至&#34;是的 - 你明白了!&#34;烤面包没有出现。

我想我错过了一些愚蠢的东西,但我找不到它。

2 个答案:

答案 0 :(得分: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 :(得分:0)

我犯了一系列错误,导致它无法正常工作。

首先:我忘了在**show()**上致电Toast.makeText()

第二:我在创建ArrayList时犯了一个大错。我在ArrayList填充了数据,然后将列表添加到HashMap,之后我调用了ArrayList.**clear()**。这导致覆盖HashMap值,这就是为什么它似乎,旋转器根本没有改变......

嗯......我觉得很傻......