(1)两种方法提冲Spinner中的数据源:通过list集合,或者是通过xml文件进行配置
(2)布局代码如下:
(3)
package com.example.spinners; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; /** * 通过继承OnItemSelectedListener接口来实现选择时的事件 * @author xuliugen * */ public class MainActivity extends Activity implements OnItemSelectedListener { private Spinner spinner1; private Spinner spinner2; // private SpinnerAdapter spinnerAdapter; private ArrayAdapteradapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner1 = (Spinner) this.findViewById(R.id.spinner1); spinner2 = (Spinner) this.findViewById(R.id.spinner2); // 第一种手工输入的list adapter = new ArrayAdapter (MainActivity.this, android.R.layout.simple_spinner_item, getDataSource()); spinner1.setAdapter(adapter); //注册监听器 spinner1.setOnItemSelectedListener(this); // 第二种:通过加载xml文件配置的数据源 ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(adapter2); } /* * 通过第一种方法:手工输入的list */ public List getDataSource() { List list = new ArrayList (); list.add("beijing"); list.add("beida"); list.add("shahai"); list.add("shangjing"); list.add("shanglian"); list.add("chengdu"); return list; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onItemSelected(AdapterView<&#63;> parent, View view, int position, long id) { String itemString = spinner1.getItemAtPosition(position).toString(); Toast.makeText(this, "你选中的是" + itemString, 1).show(); } @Override public void onNothingSelected(AdapterView<&#63;> parent) { } }
(4)资源文件中的配置如下:
<&#63;xml version="1.0" encoding="utf-8"&#63;>Spinners Settings Hello world! - Mercury
- Venus
- Earth
- Mars
- Jupiter
- Saturn
- Uranus
- Neptune
(5)运行结果如下所示:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接