Android中Spinner(下拉框)控件的使用详解

  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  List list = new ArrayList();

  list.add("苹果");

  list.add("香蕉");

  list.add("橘子");

  list.add("香蕉");

  ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);

  adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);

  Spinner sp = (Spinner) findViewById(R.id.spinner1);

  sp.setAdapter(adapter);

  sp.setOnItemSelectedListener(new OnItemSelectedListener() {

  // parent: 为控件Spinner view:显示文字的TextView position:下拉选项的位置从0开始

  public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

  TextView tvResult = (TextView) findViewById(R.id.tvResult);

  //获取Spinner控件的适配器

  ArrayAdapter adapter = (ArrayAdapter) parent.getAdapter();

  tvResult.setText(adapter.getItem(position));

  }

  //没有选中时的处理

  public void onNothingSelected(AdapterView<?> parent) {

  }

  });

  }