Spinner的定义和获取选中的值有很多种方式。
- int[] city_datas = new int[]{
- R.array.city_01,
- R.array.city_02,
- R.array.city_03,
- R.array.city_04,
- R.array.city_05,
- R.array.city_06,
- R.array.city_07,
- R.array.city_08
- };
- ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
- R.array.myfruits//单个
- , android.R.layout.simple_spinner_item);
- // Specify the layout to use when the list of choices appears
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- // Apply the adapter to the spinner
- sp3.setAdapter(adapter);
- ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(SpinnerActivity.this,android.R.layout.simple_list_item_1, cur_citys);
- private class MyBaseAdapter extends BaseAdapter{
- //上下文
- Context context;
- public MyBaseAdapter(Context context){
- this.context=context;
- }
- //数据的数量
- @Override
- public int getCount() {
- return city_datas.length;
- }
- //获取到这个条目
- @Override
- public Object getItem(int position) {
- // TODO Auto-generated method stub
- return city_datas[position];
- }
- //获取到当前条目的id
- @Override
- public long getItemId(int position) {
- // TODO Auto-generated method stub
- return position;
- }
- //返回一个视图
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- LinearLayout layout=new LinearLayout(context);
- LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
- ViewGroup.LayoutParams.FILL_PARENT);
- layout.setOrientation(LinearLayout.HORIZONTAL);
- LinearLayout.LayoutParams params2=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT);
- TextView textView=new TextView(context);
- textView.setText(this.getItem(position).toString());
- ImageView iamge=new ImageView(context);
- iamge.setImageResource(R.drawable.icon);
- layout.addView(textView, params2);
- layout.addView(iamge, params2);
- return layout;
- }
- }
- sp2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view,
- int position, long id) {
- }
- @Override
- public void onNothingSelected(AdapterView<?> arg0) {
- // TODO Auto-generated method stub
- }
- });
- sp2.getItemAtPosition(position).toString()
- sp2.getSelectedItem().toString()