Android之Spinner用法详解

  public class MainActivity extends AppCompatActivity{

  private String[] starArray = {"水星","金星","地球","火星","木星","土星"};

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  initSpinner();

  }

  private void initSpinner(){

  //声明一个下拉列表的数组适配器

  ArrayAdapter starAdapter = new ArrayAdapter(this,R.layout.item_select,starArray);

  //设置数组适配器的布局样式

  starAdapter.setDropDownViewResource(R.layout.item_dropdown);

  //从布局文件中获取名叫sp_dialog的下拉框

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

  //设置下拉框的标题,不设置就没有难看的标题了

  sp.setPrompt("请选择行星");

  //设置下拉框的数组适配器

  sp.setAdapter(starAdapter);

  //设置下拉框默认的显示第一项

  sp.setSelection(0);

  //给下拉框设置选择监听器,一旦用户选中某一项,就触发监听器的onItemSelected方法

  sp.setOnItemSelectedListener(new MySelectedListener());

  }

  class MySelectedListener implements AdapterView.OnItemSelectedListener{

  @Override

  public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

  Toast.makeText(MainActivity.this,"您选择的是:"+starArray[i],Toast.LENGTH_SHORT).show();

  }

  @Override

  public void onNothingSelected(AdapterView<?> adapterView) {

  }

  }

  }